I'm trying to deserialize this JSON to an array of Java objects of class Mural and show them in a list (Recycler View) in my app. Here's formatted example of the JSON with only the data that I need.
{
"records": [{
"recordid": "e6b10b2f7cadbe7caec9a0b36e9e7b570c3add50",
"fields": {
"auteur_s": "Dupa",
"photo": {
"id": "7cd8a2bc799826835057eaec21a28730",
},
"annee": "1994",
"coordonnees_geographiques": [50.8527886675,
4.34530735016],
"personnage_s": "Cubitus - Dommel"
},
},
...
]
}
I use Okhttp to make the request and the response is successful, so I use it to construct a JSONObject.
I traverse the "records" array in that object, because that's where I find all the data I need. Keys that have a string or an array as value work fine and I can load them into my app's Recycler View, but when I want to access "photo", i.e. a key:value pair nested within another object, I get a JSONException org.json.JSONException: No value for photo and my Recycler View returns empty.
Here's what the code looks like:
private void fetchMurals(){
threadExecutor.execute(new Runnable() {
#Override
public void run() {
OkHttpClient client = new OkHttpClient();
Request request = new Request.Builder()
.url("https://bruxellesdata.opendatasoft.com/api/records/1.0/search/?dataset=comic-book-route&rows=58")
.get()
.build();
try{
Response response = client.newCall(request).execute();
String json = response.body().string();
JSONObject jsonObject = new JSONObject(json);
JSONArray jsonRecordsArray = jsonObject.getJSONArray("records");
int arraySize = jsonRecordsArray.length();
muralArrayList = new ArrayList<>();
for (int i = 0; i < arraySize; i++){
String jsonID = jsonRecordsArray.getJSONObject(i).getString("recordid");
JSONObject jsonMural = jsonRecordsArray.getJSONObject(i).getJSONObject("fields");
JSONObject jsonMuralPhoto = jsonMural.getJSONObject("photo");
final Mural currentMural = new Mural(
jsonID,
(jsonMural.has("auteur_s")) ? jsonMural.getString("auteur_s") : "Unknown Author",
(jsonMuralPhoto.has("id")) ? jsonMuralPhoto.getString("id") : "No picture available!",
(jsonMural.has("personnage_s")) ? jsonMural.getString("personnage_s") : "Unknown character",
(jsonMural.has("annee")) ? jsonMural.getString("annee") : "Unknown year of creation",
new LatLng(jsonMural.getJSONArray("coordonnees_geographiques").getDouble(0),
jsonMural.getJSONArray("coordonnees_geographiques").getDouble(1))
);
muralArrayList.add(currentMural);
} catch (IOException e){
e.printStackTrace();
}
});
}
I've tried many variations of this but none have worked so far. Could it be a problem with my loop? Or with the jsonMural.getJSONObject("photo") that I am calling?
I see now that I was checking if my record had the field "id" whereas I should have been checking if it had "photo". I changed the line in my constructor to
(jsonArtwork.has("photo")) ? jsonArtwork.getJSONObject("photo").getString("id") : "No picture available!"
Works now.
I am trying retrieving the following JSON data from imagga's image recognition API.
{"results":[{"image":"http://docs.imagga.com/static/images/docs/sample/japan-605234_1280.jpg","tagging_id":null,"tags":[{"confidence":63.346307851163395,"tag":"valley"},{"confidence":60.66263009377379,"tag":"mountain"},{"confidence":44.39096006516168,"tag":"canyon"},{"confidence":42.08210930346856,"tag":"landscape"},{"confidence":33.52198895357515,"tag":"geological formation"},{"confidence":32.702112467737216,"tag":"mountains"},{"confidence":28.626223994488203,"tag":"glacier"},{"confidence":28.36,"tag":"natural depression"},{"confidence":28.03481906795487,"tag":"ravine"},{"confidence":27.269738461024804,"tag":"sky"},{"confidence":26.130797131953397,"tag":"rock"},{"confidence":23.11898739400327,"tag":"travel"},{"confidence":21.75182989551758,"tag":"alp"},{"confidence":20.956625061326214,"tag":"national"},{"confidence":20.15360199670358,"tag":"park"},{"confidence":19.826365024393702,"tag":"stone"},{"confidence":19.717420656127437,"tag":"water"},{"confidence":18.049071926896588,"tag":"river"},{"confidence":17.81629840041474,"tag":"hill"},{"confidence":17.30594970410163,"tag":"tourism"},{"confidence":17.192663177192692,"tag":"clouds"},{"confidence":16.53588724897844,"tag":"scenic"},{"confidence":15.98967256769248,"tag":"peak"},{"confidence":15.792599629554461,"tag":"lake"},{"confidence":15.532788988165363,"tag":"scenery"},{"confidence":15.453814687301834,"tag":"snow"},{"confidence":15.232632664896412,"tag":"outdoors"},{"confidence":15.212304004139495,"tag":"range"},{"confidence":15.042325772263556,"tag":"hiking"},{"confidence":14.958759294889424,"tag":"tree"},{"confidence":14.78842712696222,"tag":"forest"},{"confidence":12.853490785491731,"tag":"grass"},{"confidence":12.242518977753525,"tag":"desert"},{"confidence":12.095999999999998,"tag":"natural elevation"},{"confidence":12.03899501602295,"tag":"america"},{"confidence":11.49381779097963,"tag":"environment"},{"confidence":11.250534926394025,"tag":"usa"},{"confidence":10.935999552280517,"tag":"panorama"},{"confidence":10.838870815021957,"tag":"trees"},{"confidence":10.77081532273937,"tag":"south"},{"confidence":10.385222667460749,"tag":"summer"},{"confidence":9.967993711501377,"tag":"cloud"},{"confidence":9.960797892906747,"tag":"wild"},{"confidence":9.840206836878211,"tag":"natural"},{"confidence":9.64736797817423,"tag":"geology"},{"confidence":9.622992778171428,"tag":"rocky"},{"confidence":9.5011692563878,"tag":"outdoor"},{"confidence":9.36921935993258,"tag":"wilderness"},{"confidence":9.360136841263397,"tag":"vacation"},{"confidence":9.295849004816608,"tag":"rocks"},{"confidence":9.200756690906687,"tag":"high"},{"confidence":9.098263071652019,"tag":"highland"},{"confidence":8.912795414022,"tag":"tourist"},{"confidence":8.871604649828521,"tag":"hike"},{"confidence":8.849249986309006,"tag":"landmark"},{"confidence":8.696713373486205,"tag":"cliff"},{"confidence":8.600291951670297,"tag":"scene"},{"confidence":8.535889495009538,"tag":"stream"},{"confidence":8.530021520404471,"tag":"sunny"},{"confidence":8.255077489679804,"tag":"altitude"},{"confidence":8.016191292928964,"tag":"trail"},{"confidence":7.9938748285500605,"tag":"autumn"},{"confidence":7.985278417869093,"tag":"california"},{"confidence":7.927492176055299,"tag":"spain"},{"confidence":7.774043777890904,"tag":"adventure"},{"confidence":7.560207874392119,"tag":"peaceful"},{"confidence":7.485827508554503,"tag":"fall"},{"confidence":7.283862421876644,"tag":"erosion"},{"confidence":7.272123549182718,"tag":"terrain"},{"confidence":7.24510515635207,"tag":"rural"},{"confidence":7.234934522337296,"tag":"vista"},{"confidence":7.092282542389207,"tag":"holiday"}]}]}
I am using http://www.java2s.com/Code/Jar/o/Downloadorgjson20130603jar.htm library.
My Java code is as follows:
String imageUrl = "http://docs.imagga.com/static/images/docs/sample/japan-605234_1280.jpg",
apiKey = "",
apiSecret = "";
// These code snippets use an open-source library. http://unirest.io/java
HttpResponse response = Unirest.get("https://api.imagga.com/v1/tagging")
.queryString("url", imageUrl)
.basicAuth(apiKey, apiSecret)
.header("Accept", "application/json")
.asJson();
String js = response.getBody().toString();
System.out.println(js.toString());
JSONObject jObject = new JSONObject(response.getBody()); // json
System.out.print("hello");
JSONObject data1 = jObject.getJSONObject("results"); // get data
System.out.print(data1); // object
String projectname = data1.getString("tags"); // get the name
// from data.
System.out.print(projectname);
I am getting the error that
Exception in thread "main" org.json.JSONException:
JSONObject["results"] not found.
What I want to get is the list of "tag" and "confidence".
try this
JSONArray data1 = jObject.getJSONArray("results");
Edited Answer
String js = response.getBody().toString();
System.out.println(js.toString());
JSONObject jObject = new JSONObject(js); // json
System.out.print("hello");
JSONArray data1 = jObject.getJSONArray("results");
for(int i = 0; i < data1.length; i++)
{
JSONObject jsonObject = data1.getJSONObject(i);
String projectn ame = jsonObject.getString("tagging_id");
System.out.print(projectname);
JSONArray tagArray = jsonObject.getJsonArray("tags");
for(int j = 0; j < tagArray.length; j++)
{
JSONObject tagObject = tagArray.getJSON(j);
System.out.println("Tag == " + tagObject.getString("tag"));
}
}
To make your life more easy I'd go to model the Objects as POJO's and let Jackson's Objectmapper do the magic.
See http://wiki.fasterxml.com/JacksonDataBinding
I suppose you should try jObject.getJSONArray("results") instead of jObject.getJSONObject("results").
There is also a good tool to convert json to java: http://json2java.azurewebsites.net/
If you use it, you will see:
...other code...
public class RootObject
{
private ArrayList<Result> results;
public ArrayList<Result> getResults() { return this.results; }
public void setResults(ArrayList<Result> results) { this.results = results; }
}
...other code...
And results is list here, so use getJSONArray instead of getJSONObject
If you look into your json results has an array in it and therefore you should use getJSONArray and not getJSONObject.
JSONArray data1 = jObject.getJSONArray("results");
i'm trying to parse this JSON code
{
"resultCode":"350",
"message":"OK",
"result":1,
"data":
{
"totalCount":"2",
"videos":[
{
"videoId":"73bfedf534",
"VideoUrl":"www.videourlexample.com",
"title":"vbsample1",
"description":""
},
{
"videoId":"73bfedf534",
"VideoUrl":"www.videourlexample.com",
"title":"vbsample2",
"description":""
}
]
}
}
I was able to parse only this.
"resultCode":"350",
"message":"OK",
"result":1,
this is the java code
JSONObject jsonObject = (JSONObject)
//return the JSON code above.
jsonParser.parse(getHTML("...httpRequest..."));
// get a String from the JSON object
String resultCode = (String) jsonObject.get("resultCode");
System.out.println("[RESULTCODE] The message is: " + resultCode);
// get a String from the JSON object
String message = (String) jsonObject.get("message");
System.out.println("[MESSAGE] The message is: " + message);
// get a number from the JSON object
long result = (long) jsonObject.get("result");
System.out.println("[RESULT] The resultCode is: " + result);
I can't parse the "data". Someone can help me?
I would like to take each value from the json array separately... like resultCode, message and result.
Thank you.
JSONObject mainObj= new JSONObject(yourJSON);
String resultCode= mainObj.get("resultCode");
String message= mainObj.get("message");
String result= mainObj.get("result");
JSONObject dataObj = mainObj.get("data");
JSONArray jsonArray = (JSONArray) dataObj.get("videos");
for (int i = 0; i <jsonArray.length(); i++) {
JSONObject obj= jsonArray.get(i);
String videoId=obj.get("videoId");
String videoUrl=obj.get("VideoUrl");
String title=obj.get("title");
String description=obj.get("description");
System.out.println("videoId="+videoId +"videoUrl="+videoUrl+"title=title"+"description="+description);
}
System.out.println("resultCode"+resultCode+"message"+message+"result"+result);
You can try using this:-
JSONObject dataObj = (JSONObject)dataObj .get("data");
JSONArray jsonArray = (JSONArray) dataObj.get("videos");
for (int i = 0; i <jsonArray.length(); i++) {
System.out.println(((JSONObject)jsonArray.get(i)).get("videoUrl"));
}
Currently I have just printes videoUrl, you can similarly get other attributes for videos.
for data use:
int totalCount = (int) ((Map) jsonObject.get("data")).get("totalCount");
JSONArray videos = (JSONArray) jsonObject.get("data")).get("videos");
and then parse videos JSONArray.
Alright. I have a JSON Object sent to me from a server which contains the following data:
{
"result":
[
{"status":"green","type":"data1"},
{"status":"green","type":"data2"},
{"status":"green","type":"data3"}
],
"status":"ok"
}
The data I want to get is the status for the three status values. Data1, data2, and data3 always show up in that order, so I'm now trying to grab the data by index (e.g. data1 = index 0, data2 = index 1, data3 = index 2). How do I do that?
Try following:
String stat1;
String stat2;
String stat3;
JSONObject ret; //contains the original response
//Parse to get the value
try {
stat1 = ret.getJSONArray("results").getJSONObject(0).getString("status");
stat2 = ret.getJSONArray("results").getJSONObject(1).getString("status");
stat3 = ret.getJSONArray("results").getJSONObject(2).getString("status");
} catch (JSONException e1) {
e1.printStackTrace();
}
You would use JSONObject and JSONArray, the entire string is one JSONObject so you would construct one with it.
JSONObject object = new JSONObject(YOUR_STRING_OF_JSON);
Then you can access it with different get methods depending upon your expected type.
JSONArray results = object.getJSONArray("result"); // This is the node name.
String status = object.getString("status");
for (int i = 0; i < results.length(); i++) {
String resultStatus = results.getJSONObject(i).getString("status");
String type = results.getJSONObject(i).getString("type");
Log.w("JSON Result #" + i, "Status: " + resultStatus + " Type: " + type);
}
You need to surround it with a try/catch because JSON access can throw a JSONException.
Try re-factoring via a forEach loop
var testData =
{
"result":
[
{"status":"green","type":"data1"},
{"status":"green","type":"data2"},
{"status":"green","type":"data3"}
],
"status":"ok"
};
var output = new Object;
var resultSet = new Object;
resultSet = testData.result;
resultSet.forEach(function(data)
{
theStatus = data['status'];
theType = data['type']
output[theType] = theStatus;
});
console.log( output['data1'] );
If you've got your models setup to mirror that data set, then you can let GSON (https://code.google.com/p/google-gson/) do a lot of your work for you.
If you want a bit more control, and want to parse the set yourself you can use JSONObject, JSONArray. There's an example of parsing and assembling a json string here: Android create a JSON array of JSON Objects
am a android application programmer and working on JSON right now, i have a format of json, shown in below. i am getting such format form server to my android program but the problem is am unable to show the result in listview.
could provide me the logic to read that json format.
{
"1":
{
"sub1":{"marks":"10",
"maxmarks":"60",
"grade":"D"
},
"sub2":{"marks":"",
"maxmarks":"60",
"grade":""
}
},
"2":
{
"sub3":{"marks":"30",
"maxmarks":"60",
"grade":"B"
},
"sub4":{"marks":"",
"maxmarks":"60",
"grade":""
}
}
}
Use the JSONObject in Android: http://developer.android.com/reference/org/json/JSONObject.html
Here is a good tutorial: http://www.androidcompetencycenter.com/2009/10/json-parsing-in-android/
For example:
JSONObject json = new JSONObject(<your json string>);
JSONObject objectOne = json.getJSONObject("1");
JSONObject subOne = objectOne.getJSONObject("sub1");
string marksOne = subOne.getString("marks");
string maxMarksOne = subOne.getString("maxmarks");
string gradeOne = subOne.getString("grade");
There is number of libraries that can help you with the task like Jackson or GSON
What info are you trying to show in your ListView? That will help us help you parse it.
For starters you can separate the data from the two objects using...
//Assuming your original object is named responseObj
JSONObject obj1 = responseObj.getJSONObject("1");
JSONObject obj2 = responseObj.getJSONObject("2");
//Now to get each piece of data
JSONObject s1 = obj1.getJSONObject("sub1");
string marks1 = s1.getString("marks");
string maxMarks1 = s1.getString("maxmarks");
string grade1 = s1.getString("grade");
JSONObject s3 = obj2.getJSONObject("sub3");
string marks3 = s3.getString("marks");
string maxMarks3 = s3.getString("maxmarks");
string grade3 = s3.getString("grade");
From here you have all of the data and can add them to a ListView in a TextView