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.
Related
I'm trying to parse a JSON string, but getting an error when trying to get a nested object:
JSONObject jsonObject = new JSONObject(jsonString);
System.out.println(jsonObject);
System.out.println(jsonObject.keySet());
System.out.println(jsonObject.getJSONObject("matches"));
Below is the output in console. As far as I can see, the JSON is valid as jsonObject is created without an error. But when I try to obtain "matches" it throws an error. I've compared my code with tutorials but I can't see what the issue out to be:
{"matches":[{"id":233028,"awayTeam":{...
[matches, count, filters, competition]
Error in client: JSONObject["matches"] is not a JSONObject.
Anything I'm doing wrong? Happy to provide any further info if needed.
matches is an array, not an object. Use getJSONArray:
System.out.println(jsonObject.getJSONArray("matches"));
(Or more usefully:
System.out.println(Arrays.deepToString(jsonObject.getJSONArray("matches")));
since System.out.println on an array doesn't really show useful information on its own.)
To print the neccesary details we used the following command
System.out.println(msgFromServer.data);
Now the following details are fetched from server
[{id={name=XDA Studio, color=red}, angle=-0.24456912236854822, piecePosition={pieceIndex=39.0, inPieceDistance=35.797426838065036, lane={startLaneIndex=1.0, endLaneIndex=1.0}, lap=2.0}}]
How to store these above server messages in json array variable and print value of angle alone.
msgFromServer.data seems to return a List. Your List is something like
List<Map<String,Object>>
If you use Jackson parser, you could probably convert it to a Json String using the following code:
ObjectMapper mapper = new ObjectMapper();
String json = mapper.writeValueAsString(list);
I have provided code for Jackson library, you could use any other with library specific implementation and code
This question already has answers here:
How do I parse JSON in Android? [duplicate]
(3 answers)
Closed 8 years ago.
I need to parse this JSON:
{
"out":{
"nroRegistros":1,
"asignaciones":[
{
"lat":"456",
"lng":"456",
"direccion":"Nocedal 108 Estacion Central",
"depto":null,
"descripcion":"Casa amplia, cerca del metro las rejas",
"tipoVehiculo":null,
"referencia":null,
"rutDenunciante":null,
"nombreDenunciante":null,
"apePaternoDenunciante":null,
"apeMaternoDenunciante":null,
"fonoMovilDenunciante":null,
"ambito":null,
"prioridad":null,
"ley":null,
"articulo":null,
"marcaVehiculo":null,
"colorVehiculo":null,
"placaPatente":null,
"id":null
}
]
},
"status":{
"code":1,
"message":"success"
}
}
From all I have read I cant find an example or something to guide me. I am new to json and i can't really find a way to make it work. I have read a lot of tutorials but they all are quite simple. I understand them but I cant make this one work.
First of all, use some json parser to visualize data, for example http://jsonviewer.stack.hu/. This will make it for you a lot easier to understand the structure of the data.
Next step is to create a model class to accept the json you are receiving. This you have to do it by yourself, in eclipse or any other IDE you might be using.
It will look something like this:
public class JsonModel{
public Object out;
public Object status;
}
here I put Object as a general type, you may want to define the variables to an appropriate type to reflect the structure of the json file.
Once you have the model, you can simply get the data by any json library, I like to use Gson 3rd party for any json work. It would be something like so:
string json = getJsonFromInternet();
JsonModel mymodel = new Gson().fromJson(json, JsonModel.class);
your data will be stored in mymodel, as Java object, which you can use according to your needs.
I hope this helps.
find Json parsing tutorials
Json Parsing good example
You can achieve this by using JsonLib.
Try to put those values in HashMap , make sure you create the same structure of pojo classes as defined in the Json String (case sensitive)
Your json will be mapped using the classMap.put method. From there on , we have a great controller over the java bean object.
Try to explore few things, before you jump into it
String json = "{'out':[{'test':'testname'},{'test2':'testname2'}]}";
Map classMap = new HashMap();
classMap.put( "out", YourClass.class );
MyBean bean = JSONObject.toBean( JSONObject.fromObject(json), MyBean.class, classMap );
Reference
<link>http://json-lib.sourceforge.net/snippets.html</link>
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);
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]