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/
Related
How do you parse a nested JSON file like below using Processing JSON object? I am trying to figure out how to parse JSON that is multi-level.
{
"info": {
"description": "COCO 2014 Dataset",
"url": "http://cocodataset.org",
"version": "1.0",
"year": 2014,
"contributor": "COCO Consortium",
"date_created": "2017/09/01"
},
"images": [
{
"license": 5,
"file_name": "COCO_train2014_000000057870.jpg",
"coco_url": "http://images.cocodataset.org/train2014/COCO_train2014_000000057870.jpg",
"height": 480,
"width": 640,
"date_captured": "2013-11-14 16:28:13",
"flickr_url": "http://farm4.staticflickr.com/3153/2970773875_164f0c0b83_z.jpg",
"id": 57870
},
Have a look at JSONObject and JSONArray to see the available methods bellow on each page, each with documentation and examples.
Regarding your structure, here's a quick snippet on how you might access nested JSON objects and arrays:
// assume data is a JSONObject pointing to the loaded json data (via loadJSONObject / JSONObject.parse(), etc.
// access the info object
JSONObject info = data.getJSONObject("info");
// access the images array object
JSONArray images = data.getJSONArray("images");
// access a string inside an object
println(info.getString("description"));
// access a JSON object inside a JSON array
JSONObject firstImage = images.getJSONObject(0);
// acess an integer
println(firstImage.getInt("id"));
// ... and a string again
println(firstImage.getString("flickr_url"));
If you name your loaded JSONObject variable data, paste the the snippet above and run, it should print:
COCO 2014 Dataset
57870
http://farm4.staticflickr.com/3153/2970773875_164f0c0b83_z.jpg
You can use Gson to parse/deserialize to model class.
Or if you want to parse manually, then you have to parse a json object first and then you have to parse it again from a parsed json.
Eg.
JsonObject jsonObject = new JsonObject(jsonString);
JsonObject infoObject = jsonObject.getJsonObject("info");
String description = infoObject.getString("description");
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");
I have the following String passed to server:
{
"productId": "",
"sellPrice": "",
"buyPrice": "",
"quantity": "",
"bodies": [
{
"productId": "1",
"sellPrice": "5",
"buyPrice": "2",
"quantity": "5"
},
{
"productId": "2",
"sellPrice": "3",
"buyPrice": "1",
"quantity": "1"
}
]
}
which is a valid json for http://jsonlint.com/
I want to get the bodies array field.
That's how I'm doing it:
Gson gson = new Gson();
JsonObject object = gson.toJsonTree(value).getAsJsonObject();
JsonArray jsonBodies = object.get("bodies").getAsJsonArray();
But on the second line I'm getting exception listed below:
HTTP Status 500 - Not a JSON Object: "{\"productId\":\"\",\"sellPrice\":\"\",\"buyPrice\":\"\",\"quantity\":\"\",\"bodies\":[{\"productId\":\"1\",\"sellPrice\":\"5\",\"buyPrice\":\"2\",\"quantity\":\"5\"},{\"productId\":\"2\",\"sellPrice\":\"3\",\"buyPrice\":\"1\",\"quantity\":\"1\"}]}"
How to do it properly then ?
Gson#toJsonTree javadoc states
This method serializes the specified object into its equivalent
representation as a tree of JsonElements.
That is, it basically does
String jsonRepresentation = gson.toJson(someString);
JsonElement object = gson.fromJson(jsonRepresentation, JsonElement.class);
A Java String is converted to a JSON String, ie. a JsonPrimitive, not a JsonObject. In other words, toJsonTree is interpreting the content of the String value you passed as a JSON string, not a JSON object.
You should use
JsonObject object = gson.fromJson(value, JsonObject.class);
directly, to convert your String to a JsonObject.
I have used the parse method as described in https://stackoverflow.com/a/15116323/2044733 before and it's worked.
The actual code would look like
JsonParser jsonParser = new JsonParser();
jsonParser.parse(json).getAsJsonObject();
From the docs it looks like you're running into the error described where your it thinks your toJsonTree object is not the correct type.
The above code is equivalent to
JsonElement jelem = gson.fromJson(json, JsonElement.class);
as mentioned in another answer here and on the linked thread.
What about JsonArray jsonBodies = object.getAsJsonArray("bodies");
I hope someone can show me where i'm doing it wrong...
I'm using sendgrid for my email tracking and it is posting a JSON like the following:
[
{
"email": "john.doe#sendgrid.com",
"timestamp": 1337966815,
"event": "click",
"url": "http://sendgrid.com"
"userid": "1123",
"template": "welcome"
}
]
Now i want to get the value of for example for "timestamp" which is 1337966815 . I've tried the following:
StringBuffer jb = new StringBuffer();
String line = null;
try {
BufferedReader reader = req.getReader();
while ((line = reader.readLine()) != null)
jb.append(line);
} catch (Exception e) { /*report an error*/ }
String jsonString = jb.toString();
Gson gson = new Gson();
JsonObject jsonObject = gson.fromJson(jsonString, JsonObject.class);
String timeStam = jsonObject.get(timestamp).toString();
The string of jsonString gives me the following which i think is in the right format:
[ { "email": "john.doe#sendgrid.com", "timestamp": 1337966815, "event": "click", "url": "http://sendgrid.com" "userid": "1123", "template": "welcome" }]
But i'm getting the following error at this line of code - JsonObject jsonObject = gson.fromJson(jsonString, JsonObject.class);
java.lang.IllegalStateException: Expected BEGIN_OBJECT but was STRING at line 1 column 52
What am I doing wrong? Is it the format of jsonString that is confusing the JsonObject?
Any help would be very much appreciated.
Kind regards
Francois
The JSON you show in both examples is invalid. There is a comma missing after "url":"http://sendgrid.com"
Ignoring that, the JSON you show is an array of JSON objects, not an object. This is what the [] denotes (correcting the missing comma):
[
{
"email": "john.doe#sendgrid.com",
"timestamp": 1337966815,
"event": "click",
"url": "http://sendgrid.com",
"userid": "1123",
"template": "welcome"
}
]
If you are not mapping this JSON to a Java POJO, then you would want to use Gson's JsonParser to parse your String to a JsonElement (Note you could even use it to parse directly from the Stream, but this if for how you have your code now).
JsonElement je = new JsonParser().parse(jsonString);
Now you have what's called a "parse tree". This JsonElement is the root. To access it as an array you're going to do:
JsonArray myArray = je.getAsJsonArray();
You only show this array containing one object, but let's say it could have more than one. By iterating through the array you can do:
for (JsonElement e : myArray)
{
// Access the element as a JsonObject
JsonObject jo = e.getAsJsonObject();
// Get the `timestamp` element from the object
// since it's a number, we get it as a JsonPrimitive
JsonPrimitive tsPrimitive = jo.getAsJsonPrimitive("timestamp");
// get the primitive as a Java long
long timestamp = tsPrimitive.getAsLong();
System.out.println("Timestamp: " + timestamp);
}
Realize that Gson primarily is meant for Object Relational Mapping where you want to take that JSON and have it converted to a Java object. This is actually a lot simpler:
public class ResponseObject {
public String email;
public long timestamp;
public String event;
public String url;
public String userid;
public String template;
}
Because you have array of these, you want to use a TypeToken and Type to indicate your JSON is a List of these ResponseObject objects:
Type myListType = new TypeToken<List<ResponseObject>>(){}.getType();
List<ResponseObject> myList = new Gson().fromJson(jsonString, myListType);
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);