This is my JSON:
{
"results": [
{
"username": "bigglesworth",
"phone": "650-253-0000",
"createdAt": "2011-11-07T20:58:06.445Z",
"updatedAt": "2011-11-07T20:58:06.445Z",
"objectId": "3KmCvT7Zsb"
},
{
"username": "cooldude6",
"phone": "415-369-6201",
"createdAt": "2011-11-07T20:58:34.448Z",
"updatedAt": "2011-11-07T21:25:10.623Z",
"objectId": "g7y9tkhB7O"
}
]
}
How can I parse this json?
When I tried to parse this using jason I retrived this error message
"Exception in thread "main"
com.fasterxml.jackson.databind.JsonMappingException: Can not
deserialize instance of java.util.ArrayList out of START_OBJECT
token"
Without third party libraries, you can do something like
JSONObject jsonObject = new JSONObject(jsonAsString);
JSONArray results = jsonObject.getJSONArray("results");
for(int i=0; i<results.length(); i++) {
JSONObject result = results.getJSONObject(i);
String username = result.getString("username");
//...
}
Related
I have some trouble with parsing a JSON response. The response data:
{
"deal": {
"categorie": {
"description": "Offres Shopping",
"idcategorie": "1",
"nom": "Shopping"
},
"conditions": "2 personne au plus",
"dateAjout": "2013-01-07T00:00:00+01:00",
"dateExp": "2013-01-31T00:00:00+01:00",
"description": "nuit dans un hotel 5 etoile",
"heurexp": "12",
"iddeal": "1",
"minutesexp": "30",
"prestataire": {
"adresse": "Qu zohour 44",
"codePostale": "12600",
"description": "Hotel 5 etoiles",
"idprestataire": "1",
"nom": "Hotel ronald",
"pays": "France",
"telephone": "99999999",
"ville": "Brest"
},
"prix": "80.0",
"prixHabituel": "200.0",
"tags": "hotel",
"titre": "Nuit 5 etoiles"
}
}
When trying to parse this response to a List<Deal> I get this exception:
com.google.gson.JsonObject cannot be cast to com.google.gson.JsonArray
This is the code that I am using for the parse:
if (reponse != null && !reponse.isEmpty()) {
System.out.println(reponse);
Gson g = new Gson();
JsonParser parser = new JsonParser();
JsonObject jObject = parser.parse(reponse).getAsJsonObject();
JsonArray jArray = jObject.getAsJsonArray("deal"); // here goes the Exception
for (JsonElement elem : dealArray) {
deals.add(g.fromJson(elem, Deal.class));
}
System.out.println(deals.toString());
return "success";
}
thanks
Well, deal is not a JSON array, its a JSON object. Hence the exception. A JSON array, for reference, would look more like this:
"deal" : [{"attr" : "value"}, {"attr" : "value"}]
I have a JSON Arrays of Array like this
"results": [
{
"id": "AAA",
"color": "#4D4837",
"links": {
"self": "https://aaa.com",
"html": "https://bbb.com",
"download": "https://ccc.com",
"download_location": "ddd.com"
},
"categories": [],
"likes": 3891,
},
{
"id": "BBB",
"color": "#4D453",
"links": {
"self": "https://abb.com",
"html": "https://bcc.com",
"download": "https://ccc.com",
"download_location": "ddd.com"
},
"categories": [],
"likes": 3000,
}
]
And I would like to retrieve "https://bbb.com" and "https://bcc.com" of "html", but I don't know how to do that.
Based on kindly comment, I put the following.
somehow, "getJSONObject()"can not be put. The error message says "Cannot resolve method 'getJSONObject' in 'JSONArray'".
JSONArray array = new JSONArray((Collection) jobjt.get("Strings"));
for (int i =0 ; i<2 ; i++){
JSONObject job = (JSONObject) array.get(i); --> get(i) can not be changed to getJSONObject(i)
String id = job.get("id").toString();
String color = job.get("color").toString();
String photoUrl = job.get("links").toString(); --> By updating here, I want to store only "https://bbb.com" and "https://bcc.com".
}
But when I tried to use the following, not only "html", but "self" and the other information are retrieved.
String photoUrl = job.get("links").toString();
Please tell me how to retrieve only "html".
I am using IntelliJ.
Steps to be followed(assuming you have proper JSONArray you mentioned):
get JSONObject from your JSONArray by index ie. for your case, index=0 here
Get the inner JSONObject by key of links
Now, access your content by key of html
Example for your case:
JSONObject indexedObject = jsonArray.getJSONObject(0);
JSONObject linksObject = indexedObject.getJSONObject("links");
String html= linksObject.getString("html");
Better keep checking if key exists as Harshal suggests
I've been trying to figure out why constructing a org.json.JSONObject from a string json would not work for very long.
Here is the json string (pretty)
{
"status": 200,
"message": "200 Request is valid",
"job": {
"Id": 1,
"Jobtitle": "Test Job",
"Description": "Asthma",
"Medicalcondition": "Asthma",
"Language": "English",
"Racereligion": "Chinese",
"Agegender": "50, Female",
"Hourlyprice": 42,
"Type": "caregiver",
"Date": "2019-05-12T00:00:00+08:00",
"Starttime": "2018-07-20T12:15:00+08:00",
"Endtime": "2018-07-20T18:15:00+08:00",
"Address": "1 Cluny Road",
"Latitude": 1.3152057,
"Longitude": 103.8162553,
"Creator": "xiurobert"
}
}
and minified (the one that I'm attempting to construct a JSONObject from)
String json = "{\"status\":200,\"message\":\"200 Request is valid\",\"job\":{\"Id\":1,\"Jobtitle\":\"Test Job\",\"Description\":\"Asthma\",\"Medicalcondition\":\"Asthma\",\"Language\":\"English\",\"Racereligion\":\"Chinese\",\"Agegender\":\"50, Female\",\"Hourlyprice\":42,\"Type\":\"caregiver\",\"Date\":\"2019-05-12T00:00:00+08:00\",\"Starttime\":\"2018-07-20T12:15:00+08:00\",\"Endtime\":\"2018-07-20T18:15:00+08:00\",\"Address\":\"1 Cluny Road\",\"Latitude\":1.3152057,\"Longitude\":103.8162553,\"Creator\":\"xiurobert\"}}";
Constructor
JSONObject jsonObject = new JSONObject(json)
However, this resulted in a java.lang.RuntimeException: Cannot evaluate org.json.JSONObject.toString()
I've even tried using gson to parse the string first and then output it back to the new JSONObject but it seems like it didn't work.
Any reasons why?
This is working perfectly
String json = "{\"status\":200,\"message\":\"200 Request is valid\",\"job\":{\"Id\":1,\"Jobtitle\":\"Test Job\",\"Description\":\"Asthma\",\"Medicalcondition\":\"Asthma\",\"Language\":\"English\",\"Racereligion\":\"Chinese\",\"Agegender\":\"50, Female\",\"Hourlyprice\":42,\"Type\":\"caregiver\",\"Date\":\"2019-05-12T00:00:00+08:00\",\"Starttime\":\"2018-07-20T12:15:00+08:00\",\"Endtime\":\"2018-07-20T18:15:00+08:00\",\"Address\":\"1 Cluny Road\",\"Latitude\":1.3152057,\"Longitude\":103.8162553,\"Creator\":\"xiurobert\"}}";
try
{
JSONObject jsonObject = new JSONObject(json);
Log.i("TAG", "a: "+jsonObject.toString());
} catch (JSONException e)
{
e.printStackTrace();
}
where are you getting error
In my case i have used org.json.JSONObject and org.json.JSONArray. Then i changed the imports to org.json.simple.JSONObject and org.json.simple.JSONArray and my code worked without any issues.
{
"result_count": 251175,
"images": [
{
"id": "649682800",
"display_sizes": [
{
"is_watermarked": false,
"name": "thumb",
"uri": "https://media.gettyimages.com/photos/sergi-roberto-of-barcelona-celebrates-as-he-scores-their-sixth-goal-picture-id649682800?b=1&k=6&m=649682800&s=170x170&h=UjuhQ2k4pOnhCh5a1oLuC4t5rwX8332a-PEqZ8dpUfY="
}
],
"referral_destinations": [
{
"site_name": "gettyimages",
"uri": "https://www.gettyimages.com/detail/news-photo/sergi-roberto-of-barcelona-celebrates-as-he-scores-their-news-photo/649682800"
}
],
"title": "FC Barcelona v Paris Saint-Germain - UEFA Champions League Round of 16: Second Leg"
}
The above JSON Data is missing ] } . So make the data a valid JSON by adding ] } at the end
JSONObject jsonObject = new JSONObject(response);
JSONArray jsonArray = jsonObject.optJSONArray("images");
for(int i=0; i< jsonArray.length(); i++)
{
JSONObject jsonObjec = jsonArray.optJSONObject(i);
jsonObjec.optString("id");
jsonObjec.optString("title");
JSONArray display_sizes = jsonObjec.optJSONArray("display_sizes");
// get the display_sizes Array details
JSONArray referral_destinations = jsonObjec.optJSONArray("referral_destinations");
// get the referral_destinations Array details
}
First it is invalid json.
Try using gson library to parse the json.
Try this link
gson library to parse json
I want output json, but I have error
06-02 23:10:26.110: W/System.err(23235): org.json.JSONException: Value data of type java.lang.String cannot be converted to JSONObject
06-02 23:10:26.116: W/System.err(23235): at org.json.JSON.typeMismatch(JSON.java:111)
06-02 23:10:26.117: W/System.err(23235): at org.json.JSONObject.<init>(JSONObject.java:158)
06-02 23:10:26.117: W/System.err(23235): at org.json.JSONObject.<init>(JSONObject.java:171)
I create my code whith example, its my json:
{
"status": "success",
"data": {
"users_information": [
{
"id": "1",
"active": "1",
},
{
"id": "2",
"active": "1",
}]}}
It's my code:
JSONObject data = new JSONObject("data");
JSONArray userInform = data.getJSONArray("users_information");
for(int i = 0; i < userInform.length(); i++) {
JSONObject c = userInform.getJSONObject(i);
Log.e("id ", c.getString("id"));
}
String data = "{
"status": "success",
"data": {
"users_information": [
{
"id": "1",
"active": "1",
},
{
"id": "2",
"active": "1",
}]}}"
parse Json
JSONObject data = new JSONObject(data);
JSONArray userInform = data.getJSONArray("users_information");
for(int i = 0; i < userInform.length(); i++) {
JSONObject c = userInform.getJSONObject(i);
Log.e("id ", c.getString("id"));
}
The string data json can be replaced by the JSON received from backend
I dont recommend json deserialization like this. Try using at least Gson library. With it you will can create class with same structure like your json and it will parse in single line.
JSONObject data = new JSONObject("data");
You have to place the JSON String where "data" is placed. "data" is just a string and no json like you posted in your example.
If for any reason "data" is your string reference to your JSON String, then you accidentally added the quotes (") which let android interpret it as a String not a reference to a String.