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");
}
Related
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
The result i want to get:
[
{"id":1,"name":"example1","description":"An example"},
{"id":2, "name":"example2","description":"Just another example"},
... ]
To add new data to JSON i tried this:
String jsonDataString = ALL MY JSON DATA HERE;
JSONObject mainObject = new JSONObject(jsonDataString);
JSONObject valuesObject = new JSONObject();
JSONArray list = new JSONArray();
valuesObject.put("id", "3");
valuesObject.put("name", "example3");
valuesObject.put("description", "Yet another example");
list.put(valuesObject);
mainObject.accumulate("", list);
But i don't get a proper result.
And how to remove a JSON data depend on the value of the ID ?
Thank's.
To build a fresh JSONArray you can use below codes:
try {
JSONArray jsonArray = new JSONArray();
// Object 1
JSONObject jsonObject1 = new JSONObject();
jsonObject1.put("id", 1);
jsonObject1.put("name", "example1");
jsonObject1.put("description", "An example");
// Object 2
JSONObject jsonObject2 = new JSONObject();
jsonObject2.put("id", 2);
jsonObject2.put("name", "example2");
jsonObject2.put("description", "Just another example");
// Add Object 1 & 2 JSONArray
jsonArray.put(jsonObject1);
jsonArray.put(jsonObject2);
Log.d("JSON", "JSON: " + jsonArray.toString());
} catch (final JSONException e) {
Log.e("FAILED", "Json parsing error: " + e.getMessage());
}
OUTPUT:
D/JSON: JSON: [{"id":1,"name":"example1","description":"An example"},{"id":2,"name":"example2","description":"Just another example"}]
To add new JSONObject into existing JSONArray you can use below codes:
// Your Existing JSONArray
// [{"id":1,"name":"example1","description":"An example"},
// {"id":2, "name":"example2","description":"Just another example"}]
String jsonDataString = "[{\"id\":1,\"name\":\"example1\",\"description\":\"An example\"},{\"id\":2,\"name\":\"example2\",\"description\":\"Just another example\"}]";
try {
JSONArray jsonArray = new JSONArray(jsonDataString);
// Object 3
JSONObject jsonObject3 = new JSONObject();
jsonObject3.put("id", 3);
jsonObject3.put("name", "example3");
jsonObject3.put("description", "Third example");
// Add Object 3 JSONArray
jsonArray.put(jsonObject3);
Log.d("JSON", "JSON: " + jsonArray.toString());
} catch (final JSONException e) {
Log.e("FAILED", "Json parsing error: " + e.getMessage());
}
OUTPUT:
D/JSON: JSON: [{"id":1,"name":"example1","description":"An example"},{"id":2,"name":"example2","description":"Just another example"},{"id":3,"name":"example3","description":"Third example"}]
To remove JSONObject from JSONArray you can use below codes:
// Your Existing JSONArray
// [{"id":1,"name":"example1","description":"An example"},
// {"id":2,"name":"example2","description":"Just another example"},
// {"id":3,"name":"example3","description":"Third example"}]
String jsonDataString = "[{\"id\":1,\"name\":\"example1\",\"description\":\"An example\"},{\"id\":2,\"name\":\"example2\",\"description\":\"Just another example\"},{\"id\":3,\"name\":\"example3\",\"description\":\"Third example\"}]";
try {
JSONArray jsonArray = new JSONArray(jsonDataString);
Log.d("JSON", "JSON before Remove: " + jsonArray.toString());
// Remove Object id = 2
int removeId = 2;
for (int i = 0; i < jsonArray.length(); i++)
{
JSONObject object = jsonArray.getJSONObject(i);
if (object.has("id") && !object.isNull("id")) {
int id = object.getInt("id");
if (id == removeId)
{
jsonArray.remove(i);
break;
}
}
}
Log.d("JSON", "JSON After Remove: " + jsonArray.toString());
} catch (final JSONException e) {
Log.e("FAILED", "Json parsing error: " + e.getMessage());
}
OUTPUT:
D/JSON: JSON Before Remove: [{"id":1,"name":"example1","description":"An example"},{"id":2,"name":"example2","description":"Just another example"},{"id":3,"name":"example3","description":"Third example"}]
D/JSON: JSON After Remove: [{"id":1,"name":"example1","description":"An example"},{"id":3,"name":"example3","description":"Third example"}]
Hope this will help you.
The root object of the json is an array so you should use a JSONArray, not a JSONObject.
String jsonDataString = ALL MY JSON DATA HERE;
JSONArray mainObject = new JSONArray(jsonDataString);
JSONObject valuesObject = new JSONObject();
valuesObject.put("id", "3");
valuesObject.put("name", "example3");
valuesObject.put("description", "Yet another example");
mainObject.put(valuesObject);
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();
}
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");
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"));