Parsing a json Object by Xpath using JXPathContext/java - java

I want to parse a json object by xpath in java.I have tried in the following way:
JSONObject obj=new JSONObject("{\"firstName\":\"John\",\"lastName\":\"doe\",\"age\":26,\"address\":{\"streetAddress\":\"naiststreet\",\"city\":\"Nara\",\"postalCode\":\"630-0192\"},\"phoneNumbers\":[{\"type\":\"iPhone\",\"number\":\"0123-4567-8888\"},{\"type\":\"home\",\"number\":\"0123-4567-8910\"}]}");
JXPathContext context = JXPathContext .newContext(obj);
Iterator i=context.iterate("phoneNumbers[0]/type");
But i found out that the above way is not working as the Iterator doesnt contain anything.
Can anyone please let me know whether I am doing any mistake here?
Also,can anyone please let me know if there is any other better way of parsing a json object by xpath.

As highlighted in comment, the XPath is wrong due to indexes starting with 1.
The second trick is to call "toMap" on your JSONObject.
JXPath doesn't know how to deal with JSONObject, but can deal with maps.
JSONObject obj=new JSONObject("{\"firstName\":\"John\",\"lastName\":\"doe\",\"age\":26,\"address\":{\"streetAddress\":\"naiststreet\",\"city\":\"Nara\",\"postalCode\":\"630-0192\"},\"phoneNumbers\":[{\"type\":\"iPhone\",\"number\":\"0123-4567-8888\"},{\"type\":\"home\",\"number\":\"0123-4567-8910\"}]}");
JXPathContext context = JXPathContext .newContext(obj.toMap());
Iterator i=context.iterate("phoneNumbers[1]/type");

Related

How to pass json object into json array

I am new to J2EE and JSON.
I am using jsonArray.put(jsonObject) for adding a json object to a json array but its showing error message:
The method put(JSONObject) is undefined for the type JSONArray.
The library I am using for json is org.json.simple.*
Please help me out.
The method to put new stuff into an array is called add. So:
jsonArray.add(jsonObject)
should work.
Please refer to the documentation for details.

Parse serialized json payload in java

im struggling with json again :(
Here is the original response:
{"xml-fragment":{"workItem":{"#id":"251","#version":"74"},"presentation":{"#formIdenitifier":"1.0.0.201310151421/openspaceGWTPull_DefaultChannel/.default/Npda/NpdaProcess/UserReconcile/UserReconcile.gwt.json","#type":"GWT_FORM","#version":"1.0.0.201310151421","#activityName":"UserReconcile"},"workTypeDetail":{"#typePiled":"false","#pilingLimit":"0","#uid":"WT__RIoPEDWTEeOr4-yR8gXd7g","#version":"1.0.0.201310151421"},"payloadModel":{"serializedPayload":"{items:[{\"$param\":\"BankReconInput\",\"mode\":\"IN\",\"$value\":[{\"bankAccountTx_pk\":\"55213\",\"amount\":\"10099\",\"reference\":\"ImAmReference\",\"date\":\"2013-10-15\",\"reconType\":\"?\",\"amxcaseref\":\"pvm:0a12iq\",\"$type\":\"coza.npda.bom.BankTransaction\"}]}]}","#payloadMode":"JSON"}}}
i want to for example get value of amount from the serializedPayload. The problem is that it is not a json object. If i try:
obj = new JSONObject(jsonResp).getJSONObject("xml-fragment").getJSONObject("payloadModel");
this returns to me serializedPayload as a string and #payloadMode as a string.
i tried:
obj = new JSONObject(jsonResp).getJSONObject("xml-fragment").getJSONObject("payloadModel").getJSONObject("serializedPayload");
its confirms that serializedPayload is not a json object.
I looked at this example: http://developer.android.com/reference/org/json/JSONTokener.html
But its data is not as complex as mine and i am struggling to find java examples of how to do this.
Please can anyone help.
You don't need an example, you need to look at the JSON and think for a second.
serializedPayload is not a JSON object to begin with, it's really a string that has another piece of json encoded inside, sort of like the russian nesting dolls (frankly, it's an abomination).
You need to take the string, and then parse it again, using another JSONObject, sort of:
String payload = data..getJSONObject("xml-fragment").getJSONObject("payloadModel").getString("serializedPayload");
JSONObject theRealData = new JSONObject(payload);

GSON Can I convert only part of JSON, the ones I want Using GSON.fromJSON()

I am working with a big JSON object which has responses form multiple requests.
And the part I am working on requires only few object and they are not always in front.
For Example the json structure is:
**
json = {
mainDocument: {
element1: {
element11: "value11",
element12: {
element121: "value121"
}
},
element2: {
element21: {
element211: {
element2111: "value2111",
element2112: {
element21121: "value21121"
}
}
},
element22: "value22"
}
}
}
**
This structure can change depending on whether or not the request is successful.
Now,
I want to create an java object with the value of element11, element 22, element21121.
Currently I just check the json and use the setters of the object.
I want to know if there is a way to let GSON handle this and not have to parse the json myself.
Thanks in advance for any help you can offer.
I don't know if I understand your question very well, but in order to deserialize a JSON response with Gson, the most proper way in my opinion is to create a class structure that encapsulates the data in the response. In your case something like:
class Response
MainDocument mainDocument
class MainDocument
Element element1
Element element2
class Element
...
If you only need some data from the JSON, you can omit attributes in your class structure and Gson will ignore them. And if an object can have different contents in different responses, you can have something like this:
class Response
MainDocument mainDocument
Error error
And Gson will parse responses both with a root element mainDocument (like the one in the question) or with a root element error... this allows you to adapt your parsing to variable responses...
Obviously, to follow this approach, you need to know all the possible response structures you can have. If your problem is that your JSON response is absolutely variable, and you cannot create a class struture to wrap it, you always could do a manual parsing, somehting like this:
JsonParser parser = new JsonParser();
JsonObject rootObj = parser.parse(jsonString).getAsJsonObject();
String element21121 = rootObj
.getAsJsonObject("mainDocument")
.getAsJsonObject("element2")
.getAsJsonObject("element21")
.getAsJsonObject("element211")
.getAsJsonObject("element2112")
.getAsString("element21121");

Returning multiple sets of data using JSON with Java and JQuery

I want to send sets of data from servlet to the jsp using JSON. To elaborate, what exactly I want to do is take multiple rows from the database and print their values in jsp. I done with the part of DB connectivity and fetching of data. But I could not find a way to forward them to jsp using JSONObject. Each row has multiple attributes(column values). Please help me solve the problem.
What I'm doing is:
Collection <JsonObject> c=new ArrayList();
JsonObject j[] = null;
for(int i=0;i<uid_list.size();i++){//uid_list contains all the user_id's from the database
j[i].add("uid", j[i]);
j[i].add("fname", j[i]);
j[i].add("lname", j[i]);
j[i].addProperty("uid", uid_list.get(i).toString());
j[i].addProperty("fname", fname_list.get(i).toString());
j[i].addProperty("lname", lname_list.get(i).toString());
c.add(j[i]);
}
Also, is there any difference between JsonObject and JSONObject? The latter could not be recognized in servlet and by using JsonObject the put method is not recognized.
Aside from your code trying to insert into an uninitialized array, there are many JSON library for Java. You need to provide more details which one you're using
Also if your objective is just passing the JSON string into the browser, you might not even need jsp, you can just write the string version of the JSON object directly into the HttpResponse
Firstly, the JspnObject array has to be instantiated before it is used. Therefore, this means the following:
JsonObject j[] = new JsonObject[noOfObjects to be iterated]

Parsing JSONObject in javascript or Jquery

Hi friends i have a java.util.Map object in Ajax method like this..
Map<String,List<String>> sm = new TreeMap<>();
List<String> str = new ArrayList<String>();
str.add("val1");
str.add("val2");
str.add("val3");
str.add("val4");
sm.put("shift1", str);
sm.put("shift2", str);
sm.put("shift3", str);
sm.put("shift4", str);
JSONObject json = new JSONObject(sm);
response.getWriter().print(json);
In run time Map elements will be increase or decrease
according to map elements I have to generate table
This is Ajax call.. I don't know how to parse that Map object and dynamically generate the table in javascript.
Please show me how.
I am just answering your question. I don't know java and also i don't understand the details you gave above. If I am wrong, I am sorry and kindly ignore it.
To parse the string to object
In the jQuery, $.parseJSON(string);
In js, JSON.parse(string);
I hope this will help U. Thanks.
var json = $.parseJSON( jsonString );
// This one wouldn't be supported in old browsers
json = JSON.parse( jsonString );
Additionally, you could, in Java, respond with the Content-Type application/json and then in the jQuery AJAX you will receive the JSON already parsed for you.
Of course this will not happen if you specifically configure your jQuery AJAX call to receive an plain text, or HTML, or other content-type response.
For more reference, see here, at the dataType setting.

Categories