Android, Parsing JSON object - java

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/

Related

How can I find the value of an unnamed JSON object? (org.json) (java)

[Java 17 using the org.json parsing library. Not able to switch to Gson because I've written an insane amount of code in org.json :/ ]
Hello!
I am using an API in Java with the org.json JSON parsing library. I need to get the value of an unnamed JSON object in an array.
{
"lorem": [
{ // this object needs to be retrieved
"ipsum":"dolor",
"sit":"amet",
"consectetur":"adipiscing"
},
{ // this object also needs to be retrieved
"ipsum":"dolor",
"sit":"amet",
"consectetur":"adipiscing"
},
{ // this object needs to be retrieved
"ipsum":"dolor",
"sit":"amet",
"consectetur":"adipiscing"
}
]
}
Note that the entire JSON file is NOT an array, there is just one JSON array inside of a JSON object. How would I be able to get the value of all of these unnamed fields inside of the array?
Thanks in advance for any help, and also sorry if this question has been asked before, I wasn't able to find anything on it when I searched for it on Stackoverflow.
Those objects aren't really unnamed objects, they are part of an JSON array. Because they are contained in an array, we can iterate through that array and we can retrieve every object by index.
Assuming that the we read the json provided above from a file:
public static void main(String[] args) throws FileNotFoundException {
String resourceName = "src/main/resources/input.json";
InputStream inputStream = new FileInputStream(resourceName);
JSONTokener jsonTokener = new JSONTokener(inputStream);
JSONObject jsonObject = new JSONObject(jsonTokener);
// Get the array named lorem from the main object
JSONArray jsonArray = jsonObject.getJSONArray("lorem");
// Iterate through the array and get every element by index
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject object = jsonArray.getJSONObject(i);
System.out.println("ipsum:" + object.get("ipsum"));
System.out.println("sit:" + object.get("sit"));
System.out.println("consectetur:" + object.get("consectetur"));
}
}
Also, JSONObject has a toList method, which returns a List<Object>.

How to deal with json string in java servlet

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

How to extract a json object from a json array by name in java?

I'm recieving JSON from the Google Directions API and the request is like the one shown here (under Directions Responses -> Json Output) link
I don't know how to extract a particular entry from within a json array. Basically what I need is the JsonArray equivalent of JSONObject method get(String key) where you can get the entry mapped to a specific key. However, the JSONArray has no such method, and seems to only support the retrieval of info through a specific index. This is all well and good, but the google directions reponses' contents can vary - so I need a way to either find a specific key-value pairing, or loop through the entire array and have a way to check the value of the key. I could even find a way to determine the key that a JSONObject was mapped to. Any suggestions? Ex: How would you extract the distance JSONObject out of the JSONArray legs?
Edit: This is where I am stuck: Refering the the JSON example output here... I am trying to get the value of the "overview_polyline" entry within the "routes" json array. Since I cannot access the "overview_polyline" entry simply by referring to its name, I must loop through the array until I get to that entry. But how would I know when I got to that entry? Yes, perhaps I could check if the JSONObject representation of the entry had a "points" key, but that isn't necessarily exclusive to the "overview_polyline" entry. Also, I cannot simply get the (array.length() - n) entry because the number of entries returned in the array may vary. In short, it seems to me that I need a way to check the name ("overview_polyline") of each JSONObject to reliably be able to extract that information.
JSONArray routesArray = resultObj.getJSONArray("routes");
for(int i = 0; i < routesArray.length(); i++)
{
JSONObject obj = routesArray.optJSONObject(i);
if(obj != null)
{
//How do I determine if this object is the "overview_polyline"
//object?
}
}
The route is a JSONArray of JSONObject, so you have to do it this way:
JSONArray routesArray = resultObj.getJSONArray("routes");
for(int i = 0; i < routesArray.length(); i++) {
JSONObject obj = routesArray.optJSONObject(i);
if(obj != null) {
JSONObject polyline = obj.optJSONObject("overview_polyline");
}
}

JSONArray within JSONArray

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.

JSON parsing to Java - Android application

I need help with parsing json string in Java Android Appl.
Text of JSON file:
{"data":{"columns":["location_id","name","description","latitude","longitude","error","type","type_id","icon_media_id","item_qty","hidden","force_view"],"rows":[[2,"Editor","",43.076014654537,-89.399642451567,25,"Npc",1,0,1,"0","0"],[3,"Dow Recruiter","",43.07550842555,-89.399381822662,25,"Npc",2,0,1,"0","0"] [4,"Protestor","",43.074933,-89.400438,25,"Npc",3,0,1,"0","0"],[5,"State Legislator","",43.074868061524,-89.402136196317,25,"Npc",4,0,1,"0","0"],[6,"Marchers Bascom","",43.075296413877,-89.403374183615,25,"Node",22,0,1,"0","0"] [7,"Mary","",43.074997865584,-89.404967573966,25,"Npc",7,0,1,"0","0"]]},"returnCode":0,"returnCodeDescription":null}
How can get values: location_id, name, latitude, longitude.
Thanks, Michal.
Using manual parsing you can implement it like this:
JSONArray pages = new JSONArray(jsonString);
for (int i = 0; i < pages.length(); ++i) {
JSONObject rec = pages.getJSONObject(i);
JSONObject jsonPage =rec.getJSONObject("page");
String address = jsonPage.getString("url");
String name = jsonPage.getString("name");
String status = jsonPage.getString("status");
}
in your case note that your outer elemnt data is type of JSONObject and then you have a JSONArray
mine json file:
[{"page":{"created_at":"2011-07-04T12:01:00Z","id":1,"name":"Unknown Page","ping_at":"2011-07-04T12:06:00Z","status":"up","updated_at":"2011-07-04T12:01:00Z","url":"http://www.iana.org/domains/example/","user_id":2}},{"page":{"created_at":"2011-07-04T12:01:03Z","id":3,"name":"Down Page","ping_at":"2011-07-04T12:06:03Z","status":"up","updated_at":"2011-07-04T12:01:03Z","url":"http://www.iana.org/domains/example/","user_id":2}}]
note that mine starts from [, which means an array, but yours from { and then you have [ array inside. If you run it with a debugger, you can see exactly what´s inside your json objects.
There are also better approaches like:
Jackson
Jackson-JR (light-weight Jackson)
GSON
All of them can be used to convert Java Objects into their JSON representation. It can also be used to convert a JSON string to an equivalent Java object.
First of all, you need to know about Json parsing in android, so for that first read this: JSONObject, in that class, you will see the below methods:
getJSONArray(String name)
getJSONObject(String name)
getString(String name)
and many more methods to be used while implementing JSON parsing in android.
Update:
And if you are still confused then click on below link to have many examples available on web: Android JSON Parsing
You need to use the GSON lib
http://code.google.com/p/google-gson/
Object Examples
class BagOfPrimitives {
private int value1 = 1;
private String value2 = "abc";
private transient int value3 = 3;
BagOfPrimitives() {
// no-args constructor
}
}
(Serialization)
BagOfPrimitives obj = new BagOfPrimitives();
Gson gson = new Gson();
String json = gson.toJson(obj);
==> json is {"value1":1,"value2":"abc"}
Note that you can not serialize objects with circular references since that will result in infinite recursion.
(Deserialization)
BagOfPrimitives obj2 = gson.fromJson(json, BagOfPrimitives.class);
==> obj2 is just like obj
If you mean to navigate easily the Json Tree, you can use JSON Path, that is query system, similar to XPath to XML, that you can use to pick some elements in a json tree using text expressions.
http://code.google.com/p/json-path/ That's a good implementation
If you just mean that you want to parse that JSon you can use Gson from google (that is compatible with Android I guess).
This contains a complete example for your case.

Categories