Lately i have been trying to consume a Rest service which returns the below rough sample JSON. It has objects which contains Arrays and arrays contains Strings.
{
Main Object:{
Object1:{
}
Object2:{
}
Object3:{
Array1[String1,String2,String3]
Array2[String1,String2,String3]
Array3[String1,String2,String3]
Array4[String1,String2,String3]
}
}}
My requirement is to get all the arrays and check which of the specific array contains specific/required String values and than get those strings to show in jsp.
I am using Spring MVC(Rest Template) but any java based solution would do the work.
P.S: I am New to WebServices.
use JSONArray to get it from below
JSONArray jsonArray = new JSONArray();
jsonArray = JSONObject.getJSONObject("Main Object").getJSONObject("Object3").getJSONArray("Array1");
//Iterate through the above array to get required String.
for the next array :
jsonArray = JSONObject.getJSONObject("Main Object").getJSONObject("Object3").getJSONArray("Array2");
//Iterate through the second array to get required String.
Related
A variable called wrongAnswers which is an array of javascript objects is generated on the client.
It has the form
wrongAnswers = [
{"wrongAnswer": "Manzana", "wrongQuestion": "apple"},
{"wrongAnswer": "arbol", "wrongQuestion": "tree"}
]
JSON.stringify(wrongAnswers) is used and the variable is then sent to a servlet using a form.
Once it is in the servlet, i want to convert the JSON into a Java Arraylist.
I have a class Answer with 2 variables, wrongAnswer and wrongQuestion. I would like to iterate through the JSON array, and for each object, create an Answer object with the value of wrongAnswer and wrongQuestion in that JSON Object. Each time, adding the Answer object to an ArrayList so in the end, i have an ArrayList of Answers corresponding to all the values from the JSON.
At the moment, I can use request.getParameter("json") which gets me a String with the JSON data. However, i am not sure what to do with this String.
Is there a way i can easily convert a String holding JSON data into a JsonArray or JsonObject, which i can easily iterate through, getting the value of the name: value pairs in each object?
Some example code would have been nice, but there is many ways to parse and work with JSON.
One way you could try is:
JSONArray json = new JSONArray(jsonString);
ArrayList<String> array = new ArrayList<String>();
for(int index = 0; index < json.length(); index++) {
JSONObject jsonObject = json.getJSONObject(index);
String str= jsonObject.getString("wrongAnswer");
array.add(str);
}
Try using jackson for parsing the json string: https://github.com/FasterXML/jackson
For an example, look up: How to parse a JSON string to an array using Jackson
I'm currently confused why I cannot pull a JSONArray from a JSONArray in my android application. An example and a snippet of my source code are given below.
//The JSON
{
"currentPage":1,
"data":[
{
"id":"dimtrs",
"name":"Bud Light",
"breweries":[
{
"id":"BznahA",
"name":"Anheuser-Busch InBev",
}
]
}
],
"status":"success"
}
Now I'm trying to retreive the "breweries" array.
//Code Snippet
...
JSONObject jsonobject = new JSONObject(inputLine);
JSONArray jArray = jsonobject.getJSONArray("data");
JSONArray jsArray = jArray.getJSONArray("breweries");
...
I can pull objects out of the data array just fine, but I cannot get the "breweries" array from the "data" array using my current code.
The error for jsArray is:
The method .getJSONArray(int) in the type JSONArray is not applicable for the arguments String
So what is the correct way to pull the "breweries" array out of the "data" array?
Thanks for the help in advance!
It is because "breweries" is in the 1st object of the "data" array, not directly on the array itself. You are trying to get a key from an array.
So you want to call jArray.getJSONObject(0).getJSONArray("breweries"); or something to that effect.
As Sambhav Sharma explains in a comment, the reason for the error is that get methods for JSONArray expect an int and not a String as their argument.
When i call server its response is based of json object. Actually, I know how to parse JSON object but this response is strange for me. Server response is:
{"body":"Not Available!","clazz":"SoccerMatchPreview","id":{"inc":-2024241794,"machine":415106952,"new":false,"time":1337861978000,"timeSecond":1337861978},"publishedDate":"2012-06-08 17:00:00 +0100","refKey":"SoccerMatchPreview_4fb897be18be8b87f9117595","title":"Poland vs Greece"}
Those Information that I need are body, publishedDate, refKey and title. The code that i have written based of JSON object is this:
JSONObject jObject = new JSONObject(response);
JSONArray contestantObjects = jObject.getJSONArray("id");
for(int i=0; i<contestantObjects.length(); i++) {
mPreview.setBody(contestantObjects.getJSONObject(i).getString("body").toString());
mPreview.setPublishedDate(contestantObjects.getJSONObject(i).getString("publishedDate").toString());
mPreview.setRefKey(contestantObjects.getJSONObject(i).getString("refKey").toString());
mPreview.setTitle(contestantObjects.getJSONObject(i).getString("title").toString());
}
But because it doesn't have "[]" I think it's not JSON object. therefore, I wrote another code based JSON array.
JSONArray contestantObjects = new JSONArray(response);
for(int i=0; i<contestantObjects.length(); i++) {
mPreview.setBody(contestantObjects.getJSONObject(i).getString("body").toString());
mPreview.setPublishedDate(contestantObjects.getJSONObject(i).getString("publishedDate").toString());
mPreview.setRefKey(contestantObjects.getJSONObject(i).getString("refKey").toString());
mPreview.setTitle(contestantObjects.getJSONObject(i).getString("title").toString());
}
but result is same and Logcat shows:
Value {"id":{"timeSecond":1337861978,"time":1337861978000,"new":false,"machine":415106952,"inc":-2024241794},"body":"Not Available!","title":"Poland vs Greece","publishedDate":"2012-06-08 17:00:00 +0100","clazz":"SoccerMatchPreview","refKey":"SoccerMatchPreview_4fb897be18be8b87f9117595"} of type org.json.JSONObject cannot be converted to JSONArray
any suggestion would be appreciated. Thanks
JSONArray contestantObjects = jObject.getJSONArray("id");
Your error is here, id is itself a complex object, not an array.
"id":{"inc":-2024241794,"machine":415106952,"new":false,"time":1337861978000,"timeSecond":1337861978}
Therefore, after getting the id JSON object, you should be able to get the individual attributes, e.g. inc, machine, new, time, and timeSecond.
JSONObject idObject = ...getJSONObject("id");
String machine = idObject.get("machine");
A JSON array data structure would have looked like this: [] signifies an array.
For example, "Animals":["Pig", "Cat", "Dog"].
In another example, it can also be an Array of complex objects, "Animals":[{"name":"AAA", "blood":"A"}, {"name":"BBB", "blood":"B"}].
EDIT: Here is a good JSON visualizer i would recommend.
http://jsonviewer.stack.hu/
I am not sure if it possible or not but I think it can be done using JSONArray.put method.
Heres my problem:
I have got two lists:
ArrayList<Students> nativeStudents;
ArrayList<transferStudents> transferStudents = nativeStudents.getTransferStudentsList();
The JSON that I generate with transferStudents list is right here: http://jsfiddle.net/QLh77/2/ using the following code:
public static JSONObject getMyJSONObject( List<?> list )
{
JSONObject json = new JSONObject();
JsonConfig config = new JsonConfig();
config.addIgnoreFieldAnnotation( MyAppJsonIgnore.class );
if( list.size() > 0 )
{
JSONArray array = JSONArray.fromObject( list, config );
json.put( "students", array );
}
else
{
//Empty Array
JSONArray array = new JSONArray();
json.put( "students",
array );
}
return json;
}
Now what I want to get is JSON data with following structure: http://jsfiddle.net/bsa3k/1/ (Notice the tempRollNumber field in both array elements).
I was thinking of doing: (The if condition here is used for a business logic)
if(transferStudents.getNewStudentDetails().getRollNumber() == nativeStudents.getNativeStudentDetails.getStudentId()){
json.put("tempRollNumber", transferStudents.getNewStudentDetails().getRollNumber());
}
but this would add tempRollNumber outsite the array elements, I want this JSON element to be part of every entry of students array.
PS: I cant edit the transferStudents class in order to add tempRollNumber field.
Since no one has come up with anything better I'll turn my comments above into an answer.
The best way to handle this is to create an object model of your data and not create the JSON output yourself. Your app server or container can handle that for you.
Though you cannot change the objects you receive in the List you can extend the object's class to add your own fields. Those fields would then appear in the JSON when you marshall it.
Consider following piece of code:
JSONObject json = new JSONObject();
json.put("one", 1);
json.put("two", 2);
json.put("three", 3);
If i print the jsonobject it prints like this
{"three":"1","two":"2","one":"1"}
But i want like this.
{"one":"1","two":"2","three":"3"}
Please help. Thanks in advance.
The documentation at http://www.json.org/javadoc/org/json/JSONObject.html says:
A JSONObject is an unordered collection of name/value pairs.
In other words, properties of an object are accessed by name, not by position and the default serialized form does not guarantee any specific order.
Strict positioning comes only with arrays:
JSONArray json = new JSONArray();
json.put("1");
json.put("2");
json.put("3");
json.toString(); // results in ["1", "2", "3"]
The easiest workaround to solve your problem is to use the sortedKeys() method and by iterating the JSONObject key by key, produce the JSON string manually in what ever order necessary. Implementing a custom Comparator might help also.