This question already has an answer here:
org.json.JSONException: JSONObject["address"] is not a JSONArray
(1 answer)
Closed 5 years ago.
Using this code to call steam api. Parsing json gives me some problems. I manage to print the json in the console, accessing furhter data fails. Here is my code:
JSONObject json = new JSONObject(IOUtils.toString(new URL("http://api.steampowered.com/ISteamUser/GetPlayerSummaries/v0002/?key=XXXXXXX&steamids=XXXXXXX"), Charset.forName("UTF-8")));
System.out.println(json.get("response")); >>> (1)
int out = json.getJSONObject("players").getInt("steamid");
System.out.println(out);
Exception in thread "main" org.json.JSONException: JSONObject["players"] not found.
{
"response": {
"players": [
{
"steamid": "XXXXX",
"communityvisibilitystate": 3,
"profilestate": 1,
"personaname": "XXXXX",
"lastlogoff": 123123,
"profileurl": "http://steamcommunity.com/id/XXX/",
"avatar": "XXXXX",
"avatarmedium": "XXXX",
"avatarfull": "XXXXX",
"personastate": 1,
"primaryclanid": "XXX",
"timecreated": XXX,
"personastateflags": 0,
"gameextrainfo": "Tom Clancy's Rainbow Six Siege",
"gameid": "359550"
}
]
}
}
You just need to understand the difference between JSONObject structure and JSONArray structure
The JSONObject will starts with "{", and JSONArray starts with "[".
I just noticed your mistake, you didnt assign json.get("response") to any variable.
JSONObject json = new JSONObject(IOUtils.toString(new URL("http://api.steampowered.com/ISteamUser/GetPlayerSummaries/v0002/?key=XXXXXXX&steamids=XXXXXXX"), Charset.forName("UTF-8")));
System.out.println(json.get("response"));
JSONObject playersJson=json.get("response");
int out = playersJson.getJSONArray("players").getJSONObject(0).getInt("steamid");
So try changing your code as above.
Your problem is that players is not a JSONObject, it's a JSONArray which contains JSONObjects. In this case, players contains one JSONObject, so you need to access that object first using players[0]:
int out = json.getJSONArray("players")[0].getInt("steamid");
Related
I'm trying to access certain data from a JSON request, but I can't get far enough in the data to get what I need.
Site that I use: https://tibiadata.com/doc-api-v2/guilds/
The good example is the 1 under "One specific guild of Tibia"
The information I'm trying to get is the name/status under guild -> members -> characters.
This is what I do so far:
JSONObject root = new JSONObject(sb.toString()); //Get the info into root
JSONObject guildArray = root.getJSONObject("guild"); //Get the info under "guild"
JSONArray members = guildArray.getJSONArray("members"); //Get the info unders members
at this point
System.out.println(members.get(0));
would give
{"characters":[{"nick":"Coffee time","vocation":"Elite Knight","level":336,"joined":"2017-12-27","name":"Pelli Moulante","status":"online"}],"rank_title":"Leader"}
So the only part I miss, is getting into "characters" to get the name/status information.
Any idea what I'm doing wrong?
members.get(0) will return the first JsonObject in members JSONArray
{
"rank_title": "Ivory Guardian",
"characters": [
{
"name": "Tanthalas the Fourth",
"nick": "Legendary naab",
"level": 138,
"vocation": "Elder Druid",
"joined": "2008-06-17",
"status": "offline"
}, {
"name": "Bubbax",
"nick": "Deco man",
"level": 230,
"vocation": "Elder Druid",
"joined": "2014-08-29",
"status": "offline"
},
]
}
From this get the characters, JSONArray which consists of JsonObject, then iterate JSONArray using for loop
for(Object obj : members.getJsonObject(0).getJSONArray("characters")) {
JSONObject p = (JSONObject) obj;
System.out.println(p.get("name");
System.out.println(p.get("status");
}
This question already has answers here:
How do I parse JSON in Android? [duplicate]
(3 answers)
Closed 6 years ago.
I have a JSON string and I need to extract a string from it using Java (android)
The JSON string look like that :
{
"Header": {
"context": {
"change": {
"token": 3191
},
"_jsns": "urn:zimbra"
}
},
"Body": {
"AuthResponse": {
"authToken": [
{
"_content": "token"
}
],
"lifetime": 43199998,
"_jsns": "urn:zimbraAdmin"
}
},
"_jsns": "urn:zimbraSoap"
}
I want to get the value of _content, which is "token" is this case.
What i tried:
NB: result contains the json string
//result contains the json string
JSONObject jObject = new JSONObject(result);
String aJsonString = jObject.getString("Body");
JSONObject jResult = new JSONObject(aJsonString);
String aaa = jResult.getString("authToken");
At this point I get the following error :
W/System.err: org.json.JSONException: No value for authToken
Any help will be appreciated
EDIT : Java code updated
You need to traverse the JSON tree step by step
JSONObject jObject = new JSONObject(result);
JSONObject jBody = jObject.getJSONObject("Body");
JSONObject jAuthResponse = jBody.getJSONObject("AuthResponse");
JSONArray jauthToken = jAuthResponse.getJSONArray("authToken");
JSONObject jFirst = jauthToken.getJSONObject(0);
String aJsonString = jObject.getString("_content");
I have this JSON coming from one of our REST service:
[
"{\"category_name\":[\"Industry Components\"],\"categoryId\":[1]}",
"{\"category_name\":[\"Business Components\"],\"categoryId\":[2]}",
"{\"category_name\":[\"Utilities\"],\"categoryId\":[3]}",
"{\"category_name\":[\"Tools\"],\"categoryId\":[4]}
]
I am using java-json.jar to parse this JSON, this is the simple snippet where I am trying to pass above JSON string:
JSONObject jsonObject = new JSONObject(jsonStr);
But I am getting below exception:
org.json.JSONException: A JSONObject text must begin with '{' at 1 [character 2 line 1]
First I assumed it's because of [ and ] characters in JSON and I tried to replace as below:
String replacedStr = jsonStr.replaceAll("\\[", "").replaceAll("\\]", "")
But even then I am getting same exception. Can anyone please guide me to know what I am doing wrong?
I suppose that you should use not JSONObject, but JSONArray
JSON Object follows the following Structure:
{
"array": [
{
color: "red",
value: "#f00"
},
{
color: "green",
value: "#0f0"
}
]
}
JSON Array follows the following Structure:
[
{ "firstName":"John" , "lastName":"Doe" },
{ "firstName":"Anna" , "lastName":"Smith" },
{ "firstName":"Peter" , "lastName": "Jones" }
]
instead
JSONObject jsonObject = new JSONObject(jsonStr);
use
JSONArray jsonArray = new JSONArray(jsonStr);
and may be read about Gson is a nice library for parsing and work with json
If you get JSONObject text must begin with '{' exception.
Then first off all check what did u pass to the JSONObject constructor.
You should pass the right json.txt file.So make sure what are u passing to jsonobject.
String request = FileUtils.readFileToString(new File("/home/achaure/Downloads/Amol/KountRestTest/Documents/request.txt"));
JSONObject jsonObject = new JSONObject(request);
My doubt is if there is any tool on-line or not to generate a string from a JSON. For example, I have this JSON:
{
"my_json": [
{
"number": 20,
"name": "androider",
},
{
"id": 3432,
"name": "other_name",
}
]
}
If I want to declare a String in my code with this values, so I have to write many quotation marks to have my JSON in a String acceptable format.
So I want to know if thre is some tool to generate this String?
Some good choices are:
Jackson
Gson
They have built in methods to do just whatever you need to do in an efficient way...
I can't quite tell what you want from your original question, but I assume you are trying to output a Java String that contains some JSON that you have generated.
You should use JSONObject and JSONArray to accomplish this.
To create this JSON:
{
"my_json": [
{
"number": 20,
"name": "androider",
},
{
"id": 3432,
"name": "other_name",
}
]
}
You should use this code:
JSONObject a = new JSONObject();
a.put("number", 20);
a.put("name", "androider");
JSONObject b = new JSONObject();
b.put("id", 3432);
b.put("name", "other_name");
JSONArray array = new JSONArray();
array.put(a);
array.put(b);
JSONObject root = new JSONObject();
root.put("my_json", array);
// convert the root object to a string with 4 spaces of indentation
String json = root.toString(4);
As told by Angel, Jackson and Gson are two cool libs.
Gson is very easy to use while Jackson has better performance.
Try here, Go through the answers mentioned below
How to convert String to JSONObject in Java
in short,
Using org.json library:
JSONObject jsonObj = new JSONObject("{\"phonetype\":\"N95\",\"cat\":\"WP\"}");
Here put your own string.
Edit:
Try here,
http://www.mkyong.com/java/json-simple-example-read-and-write-json/
Create a Json object,
JSONObject jsonobj = new JSONObject();
Put your data using...
josnobj.put()
I have a problem with a Tastypie/Django JSON response in my Java Android code. I do GET http method to an Tastypie API and I parse the httpresponse to JSON. The problem it's that when I create a JSONArray with the json response, this throw an exception .
JSONTokener tokener = new JSONTokener(json);
finalResult = new JSONArray(json);
I get the next error message:
System.err(27193): org.json.JSONException: Value {"objects
[{"id":"1","resource_uri":"\/api\/v1\/user\/1\/","od_user":"Usuario administrador del
sitio","nick":"Admin","reg_date":"2012-08-07T15:39:20.706060+00:00"},
{"id":"2","resource_uri":"\/api\/v1\/user\/2\/","od_user":"user
test","nick":"test1","reg_date":"2012-08-08T10:44:50+00:00"}],"meta":
{"limit":20,"previous":null,"offset":0,"total_count":2,"next":null}} of type
org.json.JSONObject cannot be converted to JSONArray
W/System.err(27193): at org.json.JSON.typeMismatch(JSON.java:111)
W/System.err(27193): at org.json.JSONArray.<init>(JSONArray.java:91)
The JSON archive that I get from the tastypie API is:
{"meta": {"limit": 20, "next": null, "offset": 0, "previous": null, "total_count": 2}, "objects": [{"id": "1", "nick": "Admin", "od_user": "Usuario administrador del sitio", "reg_date": "2012-08-07T15:39:20.706060+00:00", "resource_uri": "/api/v1/user/1/"}, {"id": "2", "nick": "test1", "od_user": "user test", "reg_date": "2012-08-08T10:44:50+00:00", "resource_uri": "/api/v1/user/2/"}]}
I don't know why tastypie API JSON format can't be parsing to JSONArray.
That's because your JSON is a JSON Object and not an array. You can parse your JSON until you get to objects value and then try to convert that into a JSON array.
A JSON Array always looks like:
'[1, 2, 3, 4]'
Please note that [] is the enclosure needed for a JSON string to represent a JSON array.
it looks like a JSON Object and not a JSON Array.
try giving JSONobject instead.
JSONObject finalresult = new JSONObject(json);
JSON Array is:
["limit","next","offset"]
JSON Object is
{"limit":20, "next":null,"offset":0}
refer to this : http://www.json.org/