How to parse this JSON string - java

I'm trying to parse this string into java, but I keep getting errors.
{"id":1,"jsonrpc":"2.0","result":{"limits":{"end":3,"start":0,"total":3},"sources":[{"file":"/media/storage/media/re Music/","label":"re Music"},{"file":"/media/storage/media/ra Music/","label":"ra Music"},{"file":"addons://sources/audio/","label":"Music Add-ons"}]}}
When I use this code ...
String temp = //json code returned from up above
JSONObject obj = new JSONObject(temp);
JSONArray array = obj.getJSONArray("sources");
I get an error saying org.json.JSONObject Value... and then displays what is in temp. Any help?

The array named "sources" is several levels deep. You need to traverse down into the json.
Code formatters help with this stuff...
http://jsonformatter.curiousconcept.com/
{
"id":1,
"jsonrpc":"2.0",
"result":{
"limits":{
"end":3,
"start":0,
"total":3
},
"sources":[
{
"file":"/media/storage/media/re Music/",
"label":"re Music"
},
{
"file":"/media/storage/media/ra Music/",
"label":"ra Music"
},
{
"file":"addons://sources/audio/",
"label":"Music Add-ons"
}
]
}
}

It looks like the "sources" array is in the "result" object. So you would need to get that object and then get the array from that like this:
JSONObject obj = new JSONObject(temp);
JSONObject result = obj.getJSONObject("result");
JSONArray array = result.getJSONArray("sources");

Your json should have top level object, from there you need to get child objects. See this link for more detail.

Related

Read a specific value from JSON in Java

I am making an app in android studio using an API that returns the following:
[{"domains": ["upes.ac.in"], "country": "India", "state-province": "Dehradun", "web_pages": ["https://www.upes.ac.in/"], "name": "University of Petroleum and Energy Studies", "alpha_two_code": "IN"}]
I run it as follows:
public void onResponse(String response) {
listaUniversidades = new ArrayList<>();
JSONArray jsonArray = new JSONArray(response);
String nombreUni, pais, url;
for (int i = 0; i < jsonArray.length(); i++) {
nombreUni = jsonArray.getJSONObject(i).getString("name");
pais = jsonArray.getJSONObject(i).getString("country");
url = jsonArray.getJSONObject(i).getString("web_pages"));
texto.setText(url);
listaUniversidades.add(new Universidad(nombreUni, pais, url));
}}
The thing is that the web_pages returns the following: ["http://.www.upes.ac.in/"]
How could I make it return the correct url? Since that way I can not access the university website.
Thank you!
I will assume that you aways want to get the first "web_page" inside the "web_pages" array.
You can try to convert the "web_pages" attribute to an array before trying to get the first element, like this:
url = jsonArray
.getJSONObject(i)
.getJSONArray("web_pages"))
.getJSONObject(0)
.toString();
Have you verified that the API returns the expected value for web_pages? You can set a breakpoint on the line
String nombreUni, pais, url;
And then inspect the variable jsonArray. I think the incorrect value that you got is most likely because the API returns that value.
The problem is that "web_pages": ["https://www.upes.ac.in/"] is a JSON Array, so you need to convert it to the array and then access the appropriate item in it(presumably first one?)
It can be done the way Aleph proposed above.

JSON index out of range

I'm currently trying to process some JSON but it's given me an error saying that "Index 0 out of range [0..0)" the affected line is the one that is commented out.
JSONObject parentObject3 = new JSONObject(finalJSON3);
JSONArray parentArray3 = parentObject3.getJSONArray("players");
//JSONObject finalObject3 = parentArray3.getJSONObject(0);
tempGameBans = finalObject3.getInt("NumberOfBans");
tempVacBans = finalObject3.getInt("NumberOfMutes");;
Here is my JSON:
{
"players": [
{
"userID": "5648131",
"NumberOfBans": 0,
"NumberOfMutes": 1,
}
]
}
Edit: Currently I am only looking for 1 object per JSON URL so the Index should always be 0, unlike the possible duplicate which seems to be looking for multiple objects.
Edit 2: I found out what the issue is and it's due to the JSON not being correctly sent from my server. Thanks for the help anyway guys.
String jsonString = new String("{\"players\": [{\"userID\": \"5648131\",\"NumberOfBans\": 0,\"NumberOfMutes\": 1}]}");
JSONObject parentObject3 = new JSONObject(jsonString);
JSONArray parentArray3 = parentObject3.getJSONArray("players");
JSONObject finalObject3 = parentArray3.getJSONObject(0);
System.out.println(finalObject3.getInt("userID"));
System.out.println(finalObject3.getInt("NumberOfBans"));
System.out.println(finalObject3.getInt("NumberOfMutes"));
This is working fine, so there has to be some another issue.
You are calling some attribute either not in the JsonObject or the attribute value at that specified index doesn't exist.
Try remove the "," at the end of "NumberOfMutes": 1,.

how to construct json object using any json library/jar

I just want to construct JSON object something like this:
"Root":{
"c1": "v1"
}
I tried with the following code :
import org.codehaus.jettison.json.JSONException;
import org.codehaus.jettison.json.JSONObject;
public class Exe {
public static void main(String[] args) throws JSONException {
JSONObject object = new JSONObject("ROOT");
object.put("c1", "v1");
System.out.println(object.toString());
}
}
with this code, I got the following exception:
Exception in thread "main" org.codehaus.jettison.json.JSONException: A JSONObject text must begin with '{' at character 1 of ROOT
I played with codehaus API, but I didn't find the solution, so can you please help me on this.
You need to create the JSONObject and then add the "Root": value key-value pair to the object. The constructor accepting a String where you have "Root" expects a complete JSON object as a String.
JSONObject requestedObject = new JSONObject();
JSONObject innerValue = new JSONObject();
innerValue.put("c1", "v1");
requestedObject.put("Root", innerValue);
System.out.println(requestedObject);
has been confirmed to produce:
{"Root":{"c1":"v1"}}
As an important additional note, the JSON object you request isn't a valid JSON object. In case you're interested, you can check for valid JSON with a JSON lint tool. A valid object is shown below.
{
"Root":{
"c1": "v1"
}
}
Here's a quick snippet to confirm the statement about the constructor with a String.
JSONObject strConstr = new JSONObject("{\"Root\":{\"c1\":\"v1\"}}");
System.out.println(strConstr);
has been confirmed to produce:
{"Root":{"c1":"v1"}}

Parsing JSON in Java Using org.json

I have a large file with many JSON objects similiar to the following. I need to parse everything to get the "bought_together" items as an array using the org.json library. I'm having trouble accessing anything nested in "related".
What is the required code to retrieve "bought_together" as a list?
{
"asin": "11158732",
"title": "Girls Ballet Tutu Zebra Hot Pink",
"price": 3.17,
"imUrl": "http://ecx.images-amazon.com/images/I/51fAmVkTbyL._SY300_.jpg",
"related":
{
"also_bought": ["L00JHONN1S", "B002BZX8Z6"],
"also_viewed": ["F002BZX8Z6", "B00JHONN1S", "B008F0SU0Y", "B00D23MC6W", "B00AFDOPDA"],
"bought_together": ["D202BZX8Z6"]
},
"salesRank": {"Toys & Games": 211836},
"brand": "Coxlures",
"categories": [["Sports & Outdoors", "Other Sports", "Dance"]]
}
Here is my attempt (Please note, this is within a MapReduce program so some lines may seem out of context.):
JSONObject object = new JSONObject(sampleText); //sampleText is json that has been split by line
JSONArray boughtTogether = new JSONArray(object.getJSONArray("bought_together"));
using the following code, I hope it's help you.
//this will be your json object that contains and convert your string to jsonobject
//if you have json object already skip this.
JSONObject yourJSON = new JSONObject(targetString);
//getting the "related" jsonObject
JSONObject related = yourJSON.getJSONObject("related");
//getting the "bought_together" as an jsonArray and do what you want with it.
//you can act with jsonarray like an array
JSONArray bought_together = related.getJSONArray("bought_together");
//now if you run blow code
System.out.print(bought_together.getString(0));
//output is : D202BZX8Z6
-------update according to update the question------
you should change your code like this:
JSONObject object = new JSONObject(sampleText); //sampleText is json that has been split by line
JSONObject related = object.getJSONObject("related");
JSONArray boughtTogether = related.getJSONArray("bought_together");
-------update-------
i think you need to this point (it's not technicality all of they difference)
every thing are in {} , they will be JSONObject and the relation
is key and value like :
{"name":"ali"}
this is a jsonobject and the value of key "name" is ali and we call it
like:
myJsonObject.getString("name");
every thing are in [] ,they will be JSONArray and the relation is
index and value like :
["ali"]
this is a JsonArray the value of index 0 is ali and we call it
like:
myJsonArray.getString(0);
so in your case:
your total object is a JSONObject
the value of "related" key is still a JSONObject
the value of "bought_together" key (which is inside the value of {jsonobject} "related" key) is a JSONArray

Java android JsonArray Parser

I'm trying to parse this (for example) :
"id":"54f49b4a98686d9478ae44f5",
"title":"Free books",
"slug":"free-books",
"modules":[
[
"list",
{
"slug":"gutenberg",
"title":null,
"books":[]
}
]
]
}
How can i get the "books" array ? I use volley library.
Thanks
You can use JSONArray. Supposing you have a JSONObject called response you can get the books as following:
JSONArray modules = response.getJSONArray("modules");
JSONObject object = modules.getJSONObject(1);
JSONArray books = object.getJSONArray("book");
Take a look here in order to use it with Volley: http://www.androidhive.info/2014/09/android-json-parsing-using-volley/

Categories