java string to json element conversion - java

I am trying to convert java string object into Jsonelement by given code , but getting error for line -- JsonElement jelement = ((Object) new JsonParser()).parser(result);
BufferedReader reader=new BufferedReader(new FileReader("/home/Priyanka/Documents/json/temp.json"));
StringBuilder content=new StringBuilder();
String result=null;
String line = null;
while ((line = reader.readLine()) != null) {
content.append(line);
}
reader.close();
result= content.toString();
JsonElement jelement = ((Object) new JsonParser()).parser(result); // Error line
printJsonRecursive(result);

As Fedy2 stated on comments you are casting JsonParser to Object. Object doesn't have method parser() so it gives compilation error. Just remove that cast and compilation error should be gone.
Your JSON is missing one brace } at the end.

Related

How to access the nested field in json using Java?

I have a big JSON file(demo.json). Here is how it looks like:
{
"preview":false,
"result":{
"search_term":"rania",
"request_time":"Sat Apr 01 12:47:04 -0400 2017",
"request_ip":"127.0.0.1",
"stats_type":"stats",
"upi":"355658761",
"unit":"DR",
"job_title":"Communications Officer",
"vpu":"INP",
"organization":"73",
"city":"Wash",
"country":"DC",
"title":"Tom",
"url":"www.demo.com",
"tab_name":"People-Tab",
"page_name":"PEOPLE",
"result_number":"5",
"page_num":"0",
"session_id":"df234f468cb3fe8be",
"total_results":"5",
"filter":"qterm=rina",
"_time":"2017-04-01T12:47:04.000-0400"
}
}
{"preview"......}
{"preview"......}
....
I would like to access search term and page_name which is inside of the result and convert them into the string . Below is my java code which is not working:
BufferedReader br = new BufferedReader(new FileReader("demo.json"));
String line;
while ((line = br.readLine()) != null) {
JSONParser parser = new JSONParser();
Object obj = parser.parse(line);
JSONObject jsonObject = (JSONObject) obj;
String searchterm= (String) jsonObject.get("search_term");
String page_name = (String) jsonObject.get("page_name");
}
I am not familiar with how to access the nested fields and convert those into string. Any help is appreciated.
boolean preview = jsonObject.get("preview");
JSONObject result = jsonObject.getJSONObject("result");
String search_term = result.getString("search_term");
String page_name = result.getString("page_name");
You can use library like Gson .Convert the data into Map
BufferedReader br = new BufferedReader(new FileReader("demo.json"));
String line;
StringBuilder builder=new StringBuilder();
while ((line = br.readLine()) != null) {
builder.append(line);
}
Type type = new TypeToken<Map<String, String>>(){}.getType();
Map<String, String> myMap = gson.fromJson(builder.toString(), type);
You can use myMap to get Values for json Keys . For nested Key you can another convert it to Map again.
Use ObjectMapper to convert your JSON to PoJo and then use it.

How to extract multiple JSON Objects into String

I am reading multiple JSONObject from a file and converting into a string using StringBuilder.
These are the JSON Objects.
{"Lng":"-1.5908601","Lat":"53.7987816"}
{"Lng":"-2.5608601","Lat":"54.7987816"}
{"Lng":"-3.5608601","Lat":"55.7987816"}
{"Lng":"-4.5608601","Lat":"56.7987816"}
{"Lng":"-5.560837","Lat":"57.7987816"}
{"Lng":"-6.5608294","Lat":"58.7987772"}
{"Lng":"-7.5608506","Lat":"59.7987823"}
How to convert into a string?
Actual code is:-
BufferedReader reader = new BufferedReader(new InputStreamReader(contents.getInputStream()));
StringBuilder builder = new StringBuilder();
String line;
try {
while ((line = reader.readLine()) != null) {
builder.append(line);
}
}
catch(IOException e)
{
msg.Log(e.toString());
}
String contentsAsString = builder.toString();
//msg.Log(contentsAsString);
I tried this code
JSONObject json = new JSONObject(contentsAsString);
Iterator<String> iter = json.keys();
while(iter.hasNext())
{
String key = iter.next();
try{
Object value = json.get(key);
msg.Log("Value :- "+ value);
}catch(JSONException e)
{
//error
}
}
It just gives first object. How to loop them?
try this and see how it works for you,
BufferedReader in
= new BufferedReader(new FileReader("foo.in"));
ArrayList<JSONObject> contentsAsJsonObjects = new ArrayList<JSONObject>();
while(true)
{
String str = in.readLine();
if(str==null)break;
contentsAsJsonObjects.add(new JSONObject(str));
}
for(int i=0; i<contentsAsJsonObjects.size(); i++)
{
JSONObject json = contentsAsJsonObjects.get(i);
String lat = json.getString("Lat");
String lng = json.getString("Lng");
Log.i("TAG", lat + lng)
}
What you do is you are loading multiple JSON objects into one JSON object. This does not make sense -- it is logical that only the first object is parsed, the parser does not expect anything after the first }. Since you want to loop over the loaded objects, you should load those into a JSON array.
If you can edit the input file, convert it to the array by adding braces and commas
[
{},
{}
]
If you cannot, append the braces to the beginning of the StringBuilder and append comma to each loaded line. Consider additional condition to eliminate exceptions caused by inpropper input file.
Finally you can create JSON array from string and loop over it with this code
JSONArray array = new JSONArray(contentsAsString);
for (int i = 0; i < array.length(); ++i) {
JSONObject object = array.getJSONObject(i);
}

The method getJSONObject(String) is undefined for the type JSONObject

I am returning a json from my class:
#POST("/test")
#PermitAll
public JSONObject test(Map form) {
JSONObject json=new JSONObject();
json.put("key1",1);
json.put("key2",2);
return json;
}
now I want to get this json from "getInputStream" and parse it to see if key1 exists:
String output = "";
BufferedReader reader = new BufferedReader(new InputStreamReader(con.getInputStream()));
StringBuilder output = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
output.append(line + "\n");
}
output=output.toString();
JSONObject jsonObj = new JSONObject();
jsonObj.put("output", output);
if (jsonObj.get("output") != null){
**//search for key1 in output**
System.out.println("key1 exists");
}else{
System.out.println("key1 doesnt exist");
}
reader.close();
How can I convert output to JSONObject and search for "key1"?
I tried following but I got errors after arrows:
JSONObject jObject = new JSONObject(output); ---> The constructor JSONObject(String) is undefined
JSONObject data = jObject.getJSONObject("data"); ---> The method getJSONObject(String) is undefined for the type JSONObject
String projectname = data.getString("name"); ----> The method getString(String) is undefined for the type JSONObject
JSONObject jsonObject = (JSONObject) JSONValue.parse(output);
Try this.
And then you can verify the existence of the field using:
jsonObject.has("key1");
You need to parse the object using a parser. Check out the documentation here: https://code.google.com/p/json-simple/wiki/DecodingExamples

Parse HTTP JSONObject response in java

From the endpoint "test" I am returning a JSONObject:
#POST("/test")
#PermitAll
public JSONObject test(String name) {
JSONObject jsonval=new JSONObject();
json.put("key1",true);
json.put("key2","test");
return json;
}
in the method that checks the returned value I want to search for value of "key1".
BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
String json = null;
String res = "";
while ((res = in.readLine()) != null) {
json += res + "\n";
}
in.close();
if (jsonData has key1 with value true){
//do sth
}
else{
//do sth else
}
How can I parse the returned JSONObject?
Have you tried constructing the JSONObject from its string representation (see http://www.json.org/javadoc/org/json/JSONObject.html):
JSONObject result = new JSONObject(json)
where json is the string you've read from the InputStream
Note: you might have to strip the last new line char or even omit new lines altogether

JSON Data Formatting

I am passing the following JSON object from a .jsp page to a java servlet using JSON.stringify and JQuery.ajax():
{"bin":[{"binId":"0","binDetails":[{"productCode":"AU192","qty":"4"},{"productCode":"NE823","qty":"8"}],"comments":"store pickup"},{"binId":"1","binDetails":[{"productCode":"AF634","qty":"2"}],"comments":""},{"binId":"2","binDetails":[{"productCode":"QB187","qty":"3"}],"comments":"international shipping"},{"binId":"3","binDetails":[{"productCode":"AF634","qty":"2"},{"productCode":"QB187","qty":"2"}],"comments":""}]}
This is the code in my java servlet:
StringBuffer strBuffer = new StringBuffer();
String line = null;
try {
BufferedReader reader = request.getReader();
while((line = reader.readLine()) != null){
strBuffer.append(line);
}
} catch (Exception e) {
}
try {
JSONObject jsonObj = new JSONObject(new JSONTokener(strBuffer.toString()));
// I call a method here and pass jsonObj
} catch (Exception e) {
}
In the method to which I pass jsonObj I am using jsonObj.length() to find out how many items are in jsonObj and it tells me 1, which in this case I would have expected 3. I even tried this:
JSONObject bins = jsonObj.get("bin");
bins.length();
which told me jsonObj.get("bin") was not a JSONObject. Is my data formatted incorrectly before I pass it from my .jsp or am I using the JSONObject in my java servlet incorrectly? How do I access the values in the JSONObject?
JSONArray bins = jsonObj.getJSONArray("bin");
bins.length();

Categories

Resources