JSON index out of range - java

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,.

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.

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

Restlet throwing error when JSON begins with [

I'm using Restlet to consume a json webservice and I'm getting this error:
A JSONObject text must begin with '{' at character 1
The json response I'm getting begins with a [, which seems to be causing the issue.
Is there a way to work around this?
Here is my code:
ClientResource resource = new ClientResource(
"https://api.prosper.com/api/Listings?$top=3");
resource.setChallengeResponse(
ChallengeScheme.HTTP_BASIC, "username", "password");
Representation representation = resource.get();
JsonRepresentation jsonRepresentation = new JsonRepresentation(representation);
JSONObject jsonObject = jsonRepresentation.getJsonObject();
Json that starts with a [ is a json array. Json that starts with { is a json object.
Use JsonRepresentation#getJsonArray()
JSONArray jsonArray = jsonRepresentation.getJsonArray();
Before you continue, familiarize yourself with the json format.

How to format data in Json file with a variable assignment

I am having a converting that in to Json with following code
JSONObject jsonformatted = (JSONObject)JSONSerializer.toJSON(map);
FileWriter writer = new FileWriter("myfile.json");
It is working fine and out put is following
[ {"date":"July 4th", "event":"Independence Day"} ]
But I want the following format with a variable assign get value in Json
jsonstr = [ {"date":"July 4th", "event":"Independence Day"} ];
How can i add a variable to that
You can add a new data using put method in JSONObject
JSONObject jsonformatted = (JSONObject)JSONSerializer.toJSON(map);
jsonformatted .put("assign ", "some value")
Edit
OP wants to replace ':' with '='
Well you should not do it , because its the JSON standard.
Attributes and values are assigned using : and not by =
Check this link for more info
JSON wiki

How to parse this JSON string

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.

Categories