Parsing Json from server - java

How can i parse json like this:
{"SizeOptions": [
{
"Name": "دور باسن",
"GroupSizeId": 2,
"Id": 5,
"LangId": 0
},
{
"Name": "دور کمر",
"GroupSizeId": 2,
"Id": 6,
"LangId": 0
} ],"SizeValues": [
{
"Value": "a",
"SizeId": 11,
"SizeOptionId": 5,
"ProductId": 1069,
"Id": 145627,
"LangId": 0
},
{
"Value": "a",
"SizeId": 11,
"SizeOptionId": 8,
"ProductId": 1069,
"Id": 145630,
"LangId": 0
} ],"Sizes": [
{
"Name": "XXL",
"GroupSizeId": 2,
"Id": 11,
"LangId": 0
},
{
"Name": "L",
"GroupSizeId": 2,
"Id": 12,
"LangId": 0
}]}
I want to put all of Names in "SizeOptions" in diffrent Strings(String name1,name2,name3)
i tried this for getting started :
JSONObject jObject = new JSONObject(response);
JSONObject p = jObject.getJSONObject("SizeOptions");
String name = p.getString("Name");
but it's just giving me a "Null" value!
what's its problem? how can i fix it? Please Help

JSONObject jObject = new JSONObject(response);
JSONSONArray p = jObject.getJSONArray("SizeOptions");
for(int i=0;i<p.length();i++)
{
JSONObject jObjectValue=p.getJSONObject(i);
String name = jObjectValue.getString("Name");
}

You are trying to get a JSONArray as JSONObject. Try the following:
JSONObject jObject = new JSONObject(response);
List<String> names = new ArrayList<>();
JSONArray p = jObject.getJSONArray("SizeOptions");
for (int i = 0; i < p.length(); i++) {
JSONObject jo = p.getJSONObject(i);
String name = jo.getString("Name");
names.add(name);
}
System.out.println(names);

Related

Convert Array of key=value String to JSON in JAVA

I have multi Array key value string
For Example:
{
filters=[
{
eventConfig={
success=1.0,
bgColor=#27AE60,
successText=Yes
},
prid=9.0,
name=abc,
prqt=1.0,
price=199.89
},
{
eventConfig={
success=1.0,
bgColor=#27AE60,
successText=Yes
},
name=abc,
prid=10.0,
price=99.89,
prqt=1.0
},
{
eventConfig={
success=0.0,
bgColor=#C0392B,
successText=No
},
name=internet,
prid=11.0,
price=299.89,
prqt=1.0
},
{
eventConfig={
success=0.0,
bgColor=#C0392B,
successText=No
},
name=intermission,
prid=11.0,
price=299.89,
prqt=1.0
}
]
}
I'm trying to convert into json string but getting error while converting
i need output as
{
"filters": [
{
"eventConfig": {
"success": 1,
"bgColor": "#27AE60",
"successText": "Yes"
},
"prid": 9,
"name": "abc",
"prqt": 1,
"price": 199.89
},
{
"eventConfig": {
"success": 1,
"bgColor": "#27AE60",
"successText": "Yes"
},
"name": "abc",
"prid": 10,
"price": 99.89,
"prqt": 1
},
{
"eventConfig": {
"success": 0,
"bgColor": "#C0392B",
"successText": "No"
},
"name": "internet",
"prid": 11,
"price": 299.89,
"prqt": 1
},
{
"eventConfig": {
"success": 0,
"bgColor": "#C0392B",
"successText": "No"
},
"name": "intermission",
"prid": 11,
"price": 299.89,
"prqt": 1
}
]
}
Please use the following code snippet to Parse this response.
try {
JSONObject jsonObject = new JSONObject(response);
JSONArray filtersArray = jsonObject.getJSONArray("filters");
for (int i = 0; i < filtersArray.length(); i++) {
//Parsing eventConfig object
JSONObject eventConfigObject = filtersArray.getJSONObject(i).getJSONObject("eventConfig");
int success = eventConfigObject.getInt("success");
String bgColor = eventConfigObject.getString("bgColor");
String successText = eventConfigObject.getString("successText");
//Parsing other objects
int prid = filtersArray.getJSONObject(i).getInt("prid");
String name = filtersArray.getJSONObject(i).getString("name");
int prqt = filtersArray.getJSONObject(i).getInt("prqt");
int price = filtersArray.getJSONObject(i).getInt("price");
}
} catch (Exception e) {
e.printStackTrace();
}
Happy Coding!! Thanks..!

How to fetch json inside json inside another json?

I am new to android and json. I want to implement some logic where i can get the data from sub1 from json inside json inside another json.
Is there any way to get that data?
This is how my json file looks like.
{
"Aeronautical": [],
"Automobile": [],
"Civil": [],
"Computer": [
{
"sub1": [
{
"id": "1",
"name": "name1",
"year": "2019",
"url": "some_url"
},
{
"id": "2",
"name": "Name 2",
"year": "2018",
"url": "some url"
},
{
"id": "3",
"name": "Name 4",
"year": "2018",
"url": "some url"
}
]
}
]
}
sub1 is inside another array , so first you should get data from computer array
JSONObject obj = null;
try {
obj = new JSONObject(json);
JSONArray arr = obj.getJSONArray("Computer");
for (int i = 0; i < arr.length(); i++)
{
JSONObject obj_computers = arr.getJSONObject(i);
JSONArray sub1 = obj_computers.getJSONArray("sub1");
for (int j = 0; j < sub1 .length(); j++)
{
JSONObject sub1_data = sub1.getJSONObject(j);
Log.i("test" ,sub1_data.toString());
}
}
} catch (JSONException e) {
e.printStackTrace();
}
The Android SDK includes the org.json lib. You can use the JSONObject class.
String jsonString = /* obtain some JSON however you need to*/;
JSONObject root = new JSONObject(jsonString);
JSONObject sub1 = root.getJSONObject("sub1");
I omitted exception handling, but this is the basic idea.

I am getting error parsing the given value when tried to parse the given json format android

I have the below following type of json structure which is coming from url.
[{
"id": 1,
"name": "TV",
"fromcenter": {
"car": "60 Mins",
"bus": "20 Mins"
},
"location": {
"latitude": -33.7181,
"longitude": 10.3160
}
}, {
"id": 2,
"name": "Fridge",
"fromcenter": {
"car": "30 Mins"
},
"location": {
"latitude": -33.8433,
"longitude": 11.2411
}
}, {
"id": 3,
"name": "Mixie",
"fromcenter": {
"car": "20 Mins",
"bus": "40 Mins"
},
"location": {
"latitude": -3.8910,
"longitude": 11.27777
}
}]
I am able to parse everything except the "bus" because the bus is not available in id 2. So I am getting error as value "bus" not found. JSONException.
Let me know how to solve this? Below is what I tried.
try {
JSONArray array = new JSONArray(response);
goodModelArrayList = new ArrayList<>();
for (int i = 0; i < array.length(); i++) {
JSONObject e = array.getJSONObject(i);
spinnerModel = new MyTransport();
fromcenter = new Fromcenter();
location = new Location();
for (int j = 0; j < e.length(); j++) {
JSONObject object = e.getJSONObject("location");
latitude = object.getString("latitude");
longitude = object.getString("longitude");
}
for (int k = 0; k < e.length(); k++) {
JSONObject object = e.getJSONObject("fromcenter");
car = object.getString("car");
//bus = object.getString("bus"); //I am not able to get the bus. It throws JSONException error.
}
spinnerModel.setId(String.valueOf(e.getString("id")));
spinnerModel.setName(e.getString("name"));
spinnerModel.setFromcenter(car);
//spinnerModel.setBus(bus); //I am not able to store the datas.
spinnerModel.setLocation(latitude);
spinnerModel.setLocations(longitude);
goodModelArrayList.add(spinnerModel);
}
} catch (Exception e) {
e.printStackTrace();
}
you can interrogate if the object has the property before reading it
if (object.has("bus")) {
bus = object.getString("bus");
}
Straight forward one word.
Use optString instead of getString
optString eliminates this issue. Bus is not present in 2nd item.
So use
String bus= object.optString("bus");

Get value from JSON Response containing nested name value pairs based on a name value in Java [duplicate]

This question already has answers here:
Parsing JSON File Java [duplicate]
(7 answers)
Closed 5 years ago.
I need to get the corresponding "value" based on the "attr_id" from "full_nutrients" array in the JSON response below using Java, how can this be accomplished? For example I want to get the value when "attr_id" == 205.
JSON Response:
"foods": [
{
"food_name": "chicken noodle soup",
"brand_name": null,
"serving_qty": 1,
"serving_unit": "cup",
"serving_weight_grams": 248,
"nf_calories": 62,
"nf_total_fat": 2.36,
"nf_saturated_fat": 0.65,
"nf_cholesterol": 12.4,
"nf_sodium": 865.52,
"nf_total_carbohydrate": 7.32,
"nf_dietary_fiber": 0.5,
"nf_sugars": 0.67,
"nf_protein": 3.15,
"nf_potassium": 54.56,
"nf_p": 42.16,
"full_nutrients": [
{
"attr_id": 203,
"value": 3.1496
},
{
"attr_id": 204,
"value": 2.356
},
{
"attr_id": 205,
"value": 7.316
},
{
"attr_id": 207,
"value": 2.5048
}],
}
Your json is invalid .
You can change to this .
{"foods": [
{
"food_name": "chicken noodle soup",
"brand_name": null,
"serving_qty": 1,
"serving_unit": "cup",
"serving_weight_grams": 248,
"nf_calories": 62,
"nf_total_fat": 2.36,
"nf_saturated_fat": 0.65,
"nf_cholesterol": 12.4,
"nf_sodium": 865.52,
"nf_total_carbohydrate": 7.32,
"nf_dietary_fiber": 0.5,
"nf_sugars": 0.67,
"nf_protein": 3.15,
"nf_potassium": 54.56,
"nf_p": 42.16,
"full_nutrients": [
{
"attr_id": 203,
"value": 3.1496
},
{
"attr_id": 204,
"value": 2.356
},
{
"attr_id": 205,
"value": 7.316
},
{
"attr_id": 207,
"value": 2.5048
}],
}
}
Try this
try {
// if your response is { },you can use JSONObject
JSONObject jsonObject = new JSONObject(response);
// then find the foods tag in your json data
JSONArray foods = jsonObject.getJSONArray("foods");
// loop for the JSONArray
for (int i = 0; i < foods.length(); i++) {
// getJSONObject from the index
JSONObject jsonObject1 = foods.getJSONObject(i);
// then get full_nutrients tag
JSONArray full_nutrients = jsonObject1.getJSONArray("full_nutrients");
// loop for the JSONArray
for (int j = 0; j < full_nutrients.length(); j++) {
// getJSONObject from the index again
JSONObject jsonObject2 = full_nutrients.getJSONObject(i);
// get attr_id
String attr_id = jsonObject2.getString("attr_id");
// get value
String value = jsonObject2.getString("value");
}
}
} catch (JSONException e) {
e.printStackTrace();
}
Try this:
function Double GetValue(String json_object, int attr_id) {
Double tResult = 0;
JSONObject reader = new JSONObject(json_object);
// Getting JSON Array node
JSONArray full_nutrients = reader.getJSONArray("full_nutrients");
// looping through All full_nutrients
for (int i = 0; i < full_nutrients.length(); i++) {
JSONObject c = full_nutrients.getJSONObject(i);
if (c.getInt("attr_id") == attr_id)
tResult = c.getDouble("value");
}
return tResult;
}

How to get JSONArray exists in another JSONArray?

I have a JSONArray contained in another JSONArray in a JSON Object like the following:
{
"protocol": "test",
"query": [
{
"locked": false,
"ids": [
{
"id": 1,
"locked": false
},
{
"id": 1,
"locked": false
}
]
},
{
"locked": false,
"ids": [
{
"id": 1,
"locked": false
},
{
"id": 1,
"locked": false
}
]
}
],
}
here i want to get the ids arrays, i can get the query arrays like that:
private JSONArray getDB_Query(String json) throws JSONException{
JSONObject jsonObj = null;
try {
jsonObj = new JSONObject(json);
} catch (JSONException e) {
Login.errorMessage.setText(sys_err);
}
JSONArray query = jsonObj.getJSONArray("query");
return query;
}
Now if I want to get the ids, is that true :
jsonObj = new JSONObject(query.toString()); // query is the JSONArray I retrieved from the above method
for(int i= 0; i < query.length(); i ++){
JSONArray ids_query = jsonObj.getJSONArray("ids");
}
update your last for loop like:
for(int i= 0; i < query.length(); i ++){
JSONArray ids_query = query.getJSONObject(i).getJSONArray("ids");
}

Categories

Resources