get Json Object encased in another Json - java

i'm stuck with a JSon problem, i'm trying to get a value contained in a JSon Object witch is itself Contained in another JSon Object. The returned JSon is like this " {"id":25,"name":"aaaaaaaa:eeeeegh","dishes_number":2,"description":"tttttttttttttf","country":{"code":"FR","name":"France"},"type":{"id":2,"name":"Main course"}} "
and i want to get the value od code in Country and the id in Type
here's my code
try{
JSONArray json = new JSONArray(sb.toString());
Courses coun;
for(int i=0; i < json.length(); i++) {
JSONObject jsonObject = json.getJSONObject(i);
coun = new Courses();
// Log.i(TAG, "Nom Pays : " + jsonObject.get("name"))
coun.setName((String) jsonObject.get("name"));
coun.setId((int) jsonObject.get("id"));
coun.setCountryCode((String) jsonObject.get("code"));
coun.setDescription((String) jsonObject.get("description"));
/* coun.setCourseTypeId((int) jsonObject.get("code"));
coun.setDishesNumber((int) jsonObject.get("code")); */
repas.add(coun);
}
}catch (JSONException je){
je.printStackTrace();
};
it give me the answer " org.json.JSONException: No value for code " when i run the app
Thanks you for your help

try{
JSONArray json = new JSONArray(sb.toString());
Courses coun;
for(int i=0; i < json.length(); i++) {
JSONObject jsonObject = json.getJSONObject(i);
coun = new Courses();
// Log.i(TAG, "Nom Pays : " + jsonObject.get("name"))
coun.setName((String) jsonObject.get("name"));
coun.setId((int) jsonObject.get("id"));
//get des country
JSONObject country = jsonObject.getJSONObject("country");
//get code and other informations of country
coun.setCountryCode(country.getString("code"));
coun.setDescription((String) jsonObject.get("description"));
/* coun.setCourseTypeId((int) jsonObject.get("code"));
coun.setDishesNumber((int) jsonObject.get("code")); */
repas.add(coun);
}
}catch (JSONException je){
je.printStackTrace();
};

Code field is nested in the country, so you need to get country first:
((JSONObject)jsonObject.get("country")).get("code")
The same way you can get type and nested id field from it.
P.S. Me test code:
public static void main(String[] args) {
String jsonStr = "[{\"id\":25,\"name\":\"aaaaaaaa:eeeeegh\",\"dishes_number\":2,\"description\":\"tttttttttttttf\",\"country\":{\"code\":\"FR\",\"name\":\"France\"},\"type\":{\"id\":2,\"name\":\"Main course\"}}]";
try {
JSONArray json = new JSONArray(jsonStr);
for (int i = 0; i < json.length(); i++) {
JSONObject jsonObject = json.getJSONObject(i);
System.out.println(((JSONObject)jsonObject.get("country")).get("code"));
}
} catch (JSONException je) {
je.printStackTrace();
}
}
Output:
FR

Related

Parse JSONArray present in generic ArrayList

I have some issue with JSONArray, As I am having a JSON data present in generic ArrayList but I don't have any idea that how to parse that json data and display in list, I am using org.json library
Below is my json data which is present in array list:
[{"story":"Gaurav Takte shared a link.","created_time":"2017-02-14T19:08:34+0000","id":"1323317604429735_1307213186040177"},{"story":"Gaurav Takte shared a link.","created_time":"2017-02-02T14:22:50+0000","id":"1323317604429735_1295671703860992"},{"message":"Hurray....... INDIA WON KABBADI WORLD CUP 2016","created_time":"2016-10-22T15:55:04+0000","id":"1323317604429735_1182204335207730"},{"story":"Gaurav Takte updated his profile picture.","created_time":"2016-10-21T05:35:21+0000","id":"1323317604429735_1180682575359906"},{"message":"Friends like all of you \u2026 I would love to keep forever.\n#oldmemories with # besties \n#happydays","story":"Gaurav Takte with Avi Bhalerao and 5 others.","created_time":"2016-10-21T05:33:55+0000","id":"1323317604429735_1180682248693272"},{"message":"\"सर्वांना गणेशचतुर्थीच्या हार्दीक शुभेच्छा.\nतुमच्या मनातील सर्व मनोकामना पूर्ण होवोत , सर्वांना\nसुख, समृध्दी, ऎश्वर्य,शांती,आरोग्य लाभो हीच\nबाप्पाच्या चरणी प्रार्थना. \"\nगणपती बाप्पा मोरया , मंगलमुर्ती मोरया !!!","story":"Gaurav Takte with Avi Bhalerao and 18 others.","created_time":"2016-09-05T05:06:58+0000","id":"1323317604429735_1133207030107461"}]
And here is my code:
ArrayList data_arr1= (ArrayList) ((Map) parsed.get("posts")).get("data"); JSONArray array = new JSONArray(data_arr1); for(int i = 0; i < array.length(); i++){ try { JSONObject obj = array.getJSONObject(i); Log.p(obj.toString()); } catch (JSONException ex) { ex.printStackTrace(); } }
So how can i parse this json using org.json library.
Here is the best solution of in-proper json response.
You can try this code I hope it works good..
String result = "Your JsonArray Data Like [{}]";
ArrayList<String> arrayList = new ArrayList<>();
try {
JSONArray jsonarray = new JSONArray(result);
for (int i = 0; i < jsonarray.length(); i++) {
JSONObject jsonobject = jsonarray.getJSONObject(i);
String story = null;
try {
story = jsonobject.getString("story");
} catch (Exception e) {
e.printStackTrace();
}
String msg = null;
try {
msg = jsonobject.getString("message");
} catch (Exception e) {
e.printStackTrace();
}
String ct = jsonobject.getString("created_time");
String id = jsonobject.getString("id");
if (msg == null){
msg = "";
}
if (story == null){
story = "";
}
arrayList.add(story + msg + ct + id);
// Smodel is getter model
// arrayList.add(new Smodel(story, msg, ct, id));
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

Get Key and values from JSONObject

I am trying to extract Key and values from my JSONObject. But i am not able to do that. Here is the JSON:
[{"id":["5"]},{"Tech":["Java"]}]
It is a String initially. I have converted that to JSONObject using :
JSONObject jsonObj = new JSONObject("[{"id":["5"]},{"Tech":["Java"]}]");
Then i am trying to get the key and value by:
jsonObj.getString("id");
But its giving me null. Can anyone help me out here?
Try this:
try {
JSONArray jsonArr = new JSONArray("[{\"id\":[\"5\"]},{\"Tech\":[\"Java\"]}]");
for (int i = 0; i < jsonArr.length(); i++) {
JSONObject jsonObj = jsonArr.getJSONObject(i);
String k = jsonObj.keys().next();
Log.i("Info", "Key: " + k + ", value: " + jsonObj.getString(k));
}
} catch (JSONException ex) {
ex.printStackTrace();
}
Parameter you are sending is JsonArray and referring to JsonObject. The Correct way is
JSONObject jsonObj = new JSONObject("{'id':['5','6']},{'Tech':['Java']}");
System.out.println(jsonObj.getString("id"));
JSONArray jsonArray = new JSONArray("[{'id':['5','6','7','8']},{'Tech':['Java']}]");
System.out.println(jsonArray.length());
for(int i=0;i<jsonArray.length();i++){
System.out.println(jsonArray.getJSONObject(i).getString("id"));
}
Because at id you dont have a string , you have a array of string ,
so insted of doing this
jsonObj.getString("id");
do this
jsonObj.getArray("id"); this will give you that array in return
like if you have a Json Array at id then you have to do this
jsonObj.getJSONArray("id");

How to get some elements in nested JSON objects in a JSON array

I hava this JSON:
[
{
"title": "This a Sample title for each post_title",
"excerpt": "And this is a sample of the post_body,
"author": "King Spark",
"featured_picture": {
"source": "https://exapmple.com/blah/blah/image.jpg",
"year": "2015",
"ownwer": "Akim Man",
},
},...
From the json I only need the title, excerpt elements of the main objects. Then from the featured_picture objects, I want only the source element.
I have written this code and it seems not to be working:
private void parseData(JSONArray array){
Log.d(TAG, "Parsing array");
for(int i = 0; i<array.length(); i++) {
PostItems postItem = new PostItems();
JSONObject jsonObject = null;
try {
jsonObject = array.getJSONObject(i);
postItem.setPost_title(jsonObject.getString(ConfigPost.TAG_POST_TITLE));
postItem.setPost_body(jsonObject.getString(ConfigPost.TAG_POST_BODY));
//Parsing featured_pocture object
for (int f = 0; f<array.length(); f++) {
JSONObject object = array.getJSONObject(f);
JSONObject postImage = object.getJSONObject("featured_picture");
String imageURL = postImage.getString("source");
postItem.setPost_image(imageURL);
}
} catch (JSONException w) {
w.printStackTrace();
//Toast.makeText(this, "Error in parsing Json", Toast.LENGTH_LONG).show();
}
mPostItemsList.add(postItem);
}
}
Try to parse the nested JSON like this way:
private void parseData(JSONArray array){
Log.d(TAG, "Parsing array");
for(int i = 0; i<array.length(); i++) {
PostItems postItem = new PostItems();
JSONObject jsonObject = null;
try {
jsonObject = array.getJSONObject(i);
postItem.setPost_title(jsonObject.getString(ConfigPost.TAG_POST_TITLE));
postItem.setPost_body(jsonObject.getString(ConfigPost.TAG_POST_BODY));
//Parsing featured_picture object
JSONObject postImage = jsonObject.getJSONObject("featured_picture");
postItem.setPost_image(postImage.getString("source"));
} catch (JSONException w) {
w.printStackTrace();
//Toast.makeText(this, "Error in parsing Json", Toast.LENGTH_LONG).show();
}
mPostItemsList.add(postItem);
}
}
You won't continue read the array here
for (int f = 0; f<array.length(); f++) {
featured_picture is an entry in the map and returns a map too.
The acces should be like this :
array.getJSONObject(i).getJSONObject("featured_picture").getString("source");
You have to identify object and array in json then find value by key, once you learnt then complexity of json doesn't matter to parse follow tutorial
your code for (int f = 0; f<array.length(); f++) {
JSONObject object = array.getJSONObject(f);
JSONObject postImage = object.getJSONObject("featured_picture");
String imageURL = postImage.getString("source");
postItem.setPost_image(imageURL);
}
is not correct, this part of json is not an array but an object inside another jsonObject.
Here no need to iterate loop to read nested JSONobject.
Because "featured_picture" gives only JSONObject not an array. In case if its return array you should read like this:
JSONObject rootObject=new JSONObject();
JSONArray nestedObject=rootObject.getJSONArray("key");
Here i modified your code in correct manner hope will it help for you.
for(int i = 0; i<array.length(); i++) {
PostItems postItem = new PostItems();
JSONObject jsonObject = null;
try {
jsonObject = array.getJSONObject(i);
postItem.setPost_title(jsonObject.getString(ConfigPost.TAG_POST_TITLE));
postItem.setPost_body(jsonObject.getString(ConfigPost.TAG_POST_BODY));
//Parsing featured_pocture object
JSONObject postImage = jsonObject.getJSONObject("featured_picture");
String imageURL = postImage.getString("source");
postItem.setPost_image(imageURL);
} catch (JSONException w) {
w.printStackTrace();
//Toast.makeText(this, "Error in parsing Json", Toast.LENGTH_LONG).show();
}

how to convert json data from string variable to data to display

i am tring to convert json data from string variable like this example :
String in = "{'employees': [{'firstName':'John' , 'lastName':'Doe' },"
+ "{ 'firstName' : 'Anna' , 'lastName' :'Smith' },"
+ "{ 'firstName' : 'Peter' , 'lastName' : 'Jones' }]}";
try {
String country = "";
JSONArray Array = new JSONArray(in);
for (int i = 0; i < Array.length(); i++) {
JSONObject sys = Array.getJSONObject(i);
country += " " + sys.getString("firstName");
}
Toast.makeText(this, country, Toast.LENGTH_LONG).show();
} catch (JSONException e) {
// TODO Auto-generated catch block
Toast.makeText(this, e.toString(), Toast.LENGTH_LONG).show();
};
when i try this code i get this error :
Error parsing data org.json.JSONException: Value 0 of type java.lang.Integer cannot be
converted to JSONObject
Actually your JSON is wrong formated.
Use string as below
String in = "{\"employees\": [{\"firstName\": \"John\",\"lastName\": \"Doe\"},{\"firstName\": \"Anna\",\"lastName\": \"Smith\"},{\"firstName\": \"Peter\",\"lastName\": \"Jones\"}]}";
try {
String country = "";
JSONObject jObj = new JSONObject(in);
JSONArray jArray = jObj.getJSONArray("employees");
for(int j=0; j <jArray.length(); j++){
JSONObject sys = jArray.getJSONObject(j);
country += " " + sys.getString("firstName");
}
Toast.makeText(this, country, Toast.LENGTH_LONG).show();
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
};
Your String in is an object with key employees and value JSONArray.
So you need to parse in as a JSONObject and get the JSONArray employees from that object.
Try this
String in = "{'employees': [{'firstName':'John' , 'lastName':'Doe' },"
+ "{ 'firstName' : 'Anna' , 'lastName' :'Smith' },"
+ "{ 'firstName' : 'Peter' , 'lastName' : 'Jones' }]}";
try {
String country = "";
JSONObject jObj = new JSONObject(in);
JSONArray jArray = jObj.getJSONArray("employees");
for(int j=0; j <jArray.length(); j++){
JSONObject sys = jArray.getJSONObject(j);
country += " " + sys.getString("firstName");
}
Toast.makeText(this, country, Toast.LENGTH_LONG).show();
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
};
try below code:-
JSONObejct j = new JSONObejct(in);
JSONArray Array = j.getJSONArray("employees");
note:-
{} denote JSONObject. ({employe})
[] denote JSONArray. (employee[])
Try to replace this line :
JSONArray Array = new JSONArray(in);
With this :
JSONObject json = new JSONObject(in);
JSONArray Array = new JSONArray(json.getJSONArray("employees"));

Using Java to decode JSON array of objects

I have JSON as follows:
[{"0":"1","id":"1","1":"abc","name":"abc"},{"0":"2","id":"2","1":"xyz","name":"xyz"}]
It is an array of objects.
I need to parse it using Java. I am using the library at :
http://code.google.com/p/json-simple/downloads/list
Example 1 at this link approximates what I require:
http://code.google.com/p/json-simple/wiki/DecodingExamples
I have the following code:
/** Decode JSON */
// Assuming the JSON string is stored in jsonResult (String)
Object obj = JSONValue.parse(jsonResult);
JSONArray array = (JSONArray)obj;
JSONObject jsonObj = null;
for (int i=0;i<array.length();i++){
try {
jsonObj = (JSONObject) array.get(i);
} catch (JSONException e) {
e.printStackTrace();
}
try {
Log.d(TAG,"Object no." + (i+1) + " field1: " + jsonObj.get("0") + " field2: " + jsonObj.get("1"));
} catch (JSONException e) {
e.printStackTrace();
}
}
I am getting the following exception:
java.lang.ClassCastException: org.json.simple.JSONArray
// at JSONArray array = (JSONArray)obj;
Can someone please help?
Thanks.
Instead of casting your Object to JSONArray, you should do it like this:
JSONArray mJsonArray = new JSONArray(jsonString);
JSONObject mJsonObject = new JSONObject();
for (int i = 0; i < mJsonArray.length(); i++) {
mJsonObject = mJsonArray.getJSONObject(i);
mJsonObject.getString("0");
mJsonObject.getString("id");
mJsonObject.getString("1");
mJsonObject.getString("name");
}

Categories

Resources