How to parse a JSON in a JSON - java

i'm creating a mcq for a medical application and i'm trying to get some question from my databse with the different choice with this JSON :
{
"QCM": [{
"question": "Est-ce que Guillaume a pris?",
"id": "34",
"choix": ["Oui", "Non"]
}]
}
then i past my question string to a textview and if i have 2 choice, i create only 2 button, but only 1 button is create and in my button i have this string :
["Oui", "Non"]
So i don't understand because i create a second JSONArray loop for it ...
Here is my Java
try
{
JSONArray QCM = response.getJSONArray("QCM");
for (int i=0; i<QCM.length(); i++) {
JSONObject getQcmObject = QCM.getJSONObject(i);
String questionGet = getQcmObject.getString("question");
symptomesQuestions.setText(questionGet);
for (int x=0; x<QCM.length(); x++){
JSONObject getChoixObject = QCM.getJSONObject(x);
String choiceGet = getChoixObject.getString("choix");
lesChoixButton.setText(choiceGet);
}
}
If someone can explain me how to do it, i want to learn ! can't find any exemple for this kind of request.
Thanks folks !

you use wrong parser ,change it like this:
JSONArray QCM = response.getJSONArray("QCM");
for (int i = 0; i < QCM.length(); i++) {
JSONObject getQcmObject = QCM.getJSONObject(i);
String questionGet = getQcmObject.getString("question");
symptomesQuestions.setText(questionGet);
JSONArray choiceGet = getChoixObject.getJSONArray("choix");
lesChoixButton1.setText(choiceGet.getString(0));
lesChoixButton2.setText(choiceGet.getString(1));
}
use this site to create java pojo model from your json : http://www.jsonschema2pojo.org/

Related

Nested JSONArray

I need to read a JSON file with following form:
{
"Data":[{
"foo":"22",
"bar":"33",
"array":[
{
"1foo":"22",
"1bar":"33"
},
{
"2foo":"22",
"2bar":"33",
}
],
"anotherData":{
"foofoo":"22",
"barbar":"33"
},
"some more data":"11",
"some more data":"11"
},
{and the cycle here starts again from -->
"foo":"22",
"bar":"33",
"array":[
My question stands : How do I access individual elements given it's sometimes JSONObject and sometimes JSONArray. I tried using org.json library but I'm failing to access anything after this line -> "array":[. I tried various combinations of JSONObject and JSONArray up to no avail.
My latest code looked something like this:
List<Data> data= new ArrayList<>();
String rawJson = getJsonAsString();
JSONObject outer = new JSONObject(rawJson);
JSONArray jArr= outer.getJSONArray("Data");
JSONObject inner= outer.getJSONObject("array");
for(int i =0; i<jArr.length(); i++){
JSONObject jsonEvent = jArr.getJSONObject(i);
String foo = jsonEvent.getString("foo"); <-- this works,
String 1foo = jsonEvent.getString("1foo"); <-- but this doesn't and i cant access it
I tried dozens of different solutions(tried myself and tried to find something here as well, but every case with those nested arrays is different and I can't add those solutions together to get answer for my case)
You can increase your readability if you beautify your raw JSON string:
{
"Data":[
{
"foo":"22",
"bar":"33",
"array":[
{
"1foo":"22",
"1bar":"33"
},
{
"2foo":"22",
"2bar":"33"
}
],
"anotherData":{
"foofoo":"22",
"barbar":"33"
},
"some more data":"11",
"some more data":"11"
},
{ and the cycle here starts again from -->
"foo":"22",
"bar":"33",
"array":[
...
],
...
}
]
}
So, stick to the following code:
JSONArray jArr = outer.getJSONArray("Data");
jArr is now filled with array of your Object.
And to loop through your Object array, you can use a for-loop which you have done it correctly.
for (int i = 0; i < jArr.length(); i++) {
// The below gets your Object
JSONObject jsonEvent = jArr.getJSONObject(i);
}
And now each jsonEvent contains your Object, which you can access the Object by their type.
For example, if you would like to access foo, you can use:
String foo = jsonEvent.getString("foo"); // foo = "22"
String bar = jsonEvent.getString("bar"); // bar = "33"
// Note that your array is another Array, you need to get it as JSONArray first
JSONArray arrayJson = jsonEvent.getJSONArray("array");
And as 1foo is in the first Object for your array, you need to access it like this:
JSONObject firstObjectInArray = arrayJson.getJSONObject(0);
String target = firstObjectInArray.getString("1foo"); // target = "22"
And to access foofoo, as it is an attribute of the JSON Object anotherData, so you should obtain anotherData as JSONObject first, and then you can access foofoo:
JSONObject anotherDataObject = jsonEvent.getJSONObject("anotherData");
String foofoo = anotherDataObject.getString("foofoo"); // foofoo = "22"
So the full code within your for-loop should look like this:
for (int i = 0; i < jArr.length(); i++) {
// The below gets your Object
JSONObject jsonEvent = jArr.getJSONObject(i);
String foo = jsonEvent.getString("foo");
JSONArray arrayJson = jsonEvent.getJSONArray("array");
String target = arrayJson.getJSONObject(0).getString("1foo");
// Add to get foofoo
JSONObject anotherDataObject = jsonEvent.getJSONObject("anotherData");
String foofoo = anotherDataObject.getString("foofoo");
}

Reading JSON from Java

I have this JSON structure:
{"metrics":[{
"type": "sum",
"column": ["rsales", "nsales"]
},
{
"type":"count",
"column":["ptype", "plan"]
}]
}
I am trying to read that JSON from Java and want to the output to be like:
str_sum="Sum"
str_sum_array[]= {"rsales" ,"nsales"}
str_count="count"
str_count_array[]= {"ptype" ,"plan"}
Here is my code so far:
JSONArray jsonArray_Metric = (JSONArray) queryType.get("metrics");
for (int i = 0; i < jsonArray_Metric.length(); i++) {
JSONObject json_Metric = jsonArray_Metric.getJSONObject(i);
Iterator<String> keys_Metrict = json_Metric.keys();
while (keys_Metrict.hasNext()) {
String key_Metric = keys_Metrict.next();
// plz help
}
}
How can I complete the code to produce the desired output?
Instead of using iterator you can use simple for-loop as below ..
JSONParser parser = new JSONParser();
JSONObject object = (JSONObject) parser.parse(queryType);
JSONArray jsonArray_Metric = (JSONArray) object.get("metrics");
for (int index = 0; index < jsonArray_Metric.size(); index++) {
JSONObject item = (JSONObject) jsonArray_Metric.get(index);
String type = (String) item.get("type");
JSONArray column = (JSONArray) item.get("column");
System.out.println("str_sum store=\"" + type + "\"");
System.out.println("str_count_array[] store=" + column);
}
Sample Run
str_sum store="sum"
str_count_array[] store=["rsales","nsales"]
str_sum store="count"
str_count_array[] store=["ptype","plan"]
If you want JSONArray to be displayed with curly braces instead of default (actual) braces i.e. square braces then you could so something like this while printing or you can even delete them by replacing them with empty string "".
System.out.println("str_count_array[] store " + column.toString().replace("[", "{").replace("]", "}"));
You can format your display code as you like by playing around with println statement.

Parse Json in Java not working [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions concerning problems with code you've written must describe the specific problem — and include valid code to reproduce it — in the question itself. See SSCCE.org for guidance.
Closed 9 years ago.
Improve this question
I have the following json:
{
"count" : "1567",
"program" : ["NDBC Meteorological\/Ocean", "International Partners"],
"owner" : ["NDBC", "Alaska Ocean Observing System"],
"station" : [{
"id" : "00922",
"lat" : "30",
"lon" : "-90",
"name" : "OTN201 - 4800922"
}
]
}
I need just to get station information like the id, lat, lon, name etc. But I cannot get it to work, here's my code:
//////response_str is the json string///////
JSONArray pages = new JSONArray(response_str);
for (int i = 0; i < pages.length(); ++i) {
JSONObject rec = pages.getJSONObject(i);
JSONObject jsonPage =rec.getJSONObject("station");
String name= jsonPage.getString("name");
System.out.println(name);
}
Any help will be greatly appreciated, Regards
station is JSONArray instead of JSONObject so you will need to first get JSONArray from main JSONObject then extract all id,lat,lon,.. from JSONObject. change your code as:
JSONArray pages = new JSONArray(response_str);
for (int i = 0; i < pages.length(); ++i) {
JSONObject rec = pages.getJSONObject(i);
JSONArray jsonPage =rec.getJSONArray("station");
// get JSONObject
JSONObject jsonstation =jsonPage.getJSONObject(0);
String name= jsonstation.getString("name");
System.out.println(name);
}
The root is a JSONObject not a JSONArray and it contains, three JSONArray named programm, station and owner and the count field. You should change your code accordingly with the JSON structure
You don't need the outside loop at all
JSONObject jMain = new JSONObject( response_str);
JSONArray jStationList =jMain.getJSONArray("station");
JSONObject jStation =jStationList.getJSONObject(0);
String name= jsonstation.getString("name");
..etc
You're issue is that you're referring to the source string as a JSONArray when it is instead a JSONObject (brackets on the outside would indicate that is an array). The following gets the name of the station.
JSONObject pages = new JSONObject(response_str);
for (int i = 0; i < pages.length(); ++i)
{
JSONArray stationInfo =rec.getJSONArray("station");
String name= stationInfo.getString("name");
System.out.println(name);
}

Mapping JSON to arrays/objects in Java - Android

I have a web system that returns a json string with the data that I need in an Android App. The string is below:
[
{"id":1,
"title":"Remove ViRuSeS",
"tagline":"Remove ViRuSeS",
"body":"Body",
"image":"index.jpg",
"steps":[
{"id":2,
"title":"Step 1",
"body":"Download Things!",
"position":1}
]
}
]
It should return an array of objects, with one of the object's items also being an array of items.
I am familiar with gson and have gotten this working in the past, but I always had to simplify my data down to just an object, which makes me end up have to make multiple calls to get the data.
Is there a good way to do this without having to map all of the possible values back into classes?
My last attempt was to just try to get something simple out of this and am getting a NullPointerException on the second of these lines:
userDet = new JSONObject(string);
JSONArray userDetJson = userDet.getJSONArray("Steps");
change it to "steps" and not "Steps" , It will fix it:
userDet = new JSONObject(string);
JSONArray userDetJson = userDet.getJSONArray("steps");
The full parsing method:
JSONArray mainArray = new JSONArray(json);
for (int i = 0 ; i < mainArray.length() ; i ++)
{
JSONObject currentItem = array.getJSONObject(i);
String title = currentItem.getString("title");
String body = currentItem.getString("body ");
....
JSONArray currentItemStepsArray = currentItem.getJSONArray("steps");
for (int j = 0 ; j < currentItemStepsArray.length() ; j ++)
{
....
}
}
Here, try this:
JSONArray topLevelArr = new JSONArray(json);
JSONArray stepArr = topLevelArr.getJSONObject(0).getJSONArray("steps");

How can parse my json result

I am working in android. I want to parse my json data.
This is my json data:-
{
"response":{
"groups":[
{
"type":"nearby",
"name":"Nearby",
"items":[
{
"id":"4ed0c8f48231b9ef88fe5f09",
"name":"Banayan Tree School",
"contact":{
},
"location":{
"lat":26.857954980225713,
"lng":75.76602927296061,
"distance":510
},
"categories":[
{
"id":"4bf58dd8d48988d1a8941735",
"name":"General College & University",
"pluralName":"General Colleges & Universities",
"shortName":"Other - Education",
"icon":"https:\/\/foursquare.com\/img\/categories\/education\/default.png",
"parents":[
"Colleges & Universities"
],
"primary":true
}
],
"verified":false,
"stats":{
"checkinsCount":5,
"usersCount":4,
"tipCount":0
},
"hereNow":{
"count":0
}
}
]
}
]
}
}
i want to use icon to show icon in imageview. please suggest me how can i get this icon value and how can i user this icon url in imageview.
Thank you in advance.
i am trying this, but still it is creating error:-
this is my code:- but still is creating error:-
JSONArray groups= (JSONArray) jsonObj.getJSONObject("response").getJSONArray("groups");
int length= groups.length(); if (length > 0){ for (int i = 0; i < length; i++)
{
JSONObject group= (JSONObject) groups.get(i); JSONArray items =(JSONArray) group.getJSONArray("items");
for (int j = 0; j < items.length(); j++)
{
JSONObject item = (JSONObject) items.get(j);
JSONObject iconobject=(JSONObject) item.getJSONObject("categories");//this is creating error that JSON.typeMismatch
venue.icon=iconobject.getString("icon");
}}}}
The class JSONObject can help you:
String data = ... // your json data
JSONObject json = new JSONObject(data);
You can access nodes in your structure with help of getJSONObject(String) and getJSONArray(String).
For example:
JSONObject response = json.getJSONObject("response");
JSONArray groups = response.getJSONArray("groups");
JSONObject firstGroup = groups.getJSONObject(0);
// and so on
When you got your node that contains your icon value you can use the getString(String) method to get the icon url:
JSONObject firstCategory = categories.getJSONObject(0);
String iconUrl = firstCategory.getString("icon");
After you got the url you have to download the image before you can use it. How to download an image from an url is described here
When you downloaded the image you can update the imageview:
Bitmap image = loadBitmap(iconUrl); // how to implement loadBitmap is shown in the link above
ImageView iv = findViewById(R.id.my_imageview);
iv.setImageBitamp(image);
Try this:
try {
JSONArray jArray = new JSONArray(result);
// get into the 'groups' array
JSONObject jData = jArray.getJSONObject(0);
JSONArray jGroupsArray = jData.getJSONArray("groups");
// get into the 'items' array
jData = jArray.getJSONObject(2);
JSONArray jItemsArray = jData.getJSONArray("items");
// get into the 'categories' array
jData = jArray.getJSONObject(4);
JSONArray jCategoriesArray = jData.getJSONArray("categories");
// get into the 'icon' value as String and use it as you please
jData = jArray.getJSONObject(4);
String iconURL = jData.getString("icon");
} catch (JSONException e) {
Log.e(Constants.LOG_TAG, "Error parsing data", e);
}
Hope this helps
Refer to the JSON documentation: http://www.json.org/javadoc/org/json/package-summary.html. It's really simple.
In your case, you would have to read the JSON string to a JSON object, then parse "response" as a JSONObject, "groups" as a JSONArray inside "response", iterate through the JSONObjects contained in the "groups" array, parse "Items" as a JSONArray inside your JSONObject, and son on...
You should be able to get to the URL in no time.

Categories