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");
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
This question already has answers here:
Json object returning null against given key
(3 answers)
Closed 5 years ago.
Here's the JSON response.
The following works:
jsonObject.get("title").getAsString();
jsonObject.get("author").getAsJsonObject().get("profile_photo").getAsString();
but jsonObject.get("primary_photo").getAsString() (from line 60) returns an Unsupported Exception: null error. I've tried replacing getAsString() with toString() but the latter returns an empty string.
Try this
Use optJSONObject and optString in your code . And the root is [],so you should use JSONArray
try {
JSONArray jsonArray = new JSONArray(response);
for (int i = 0; i < jsonArray.length(); i++) {
// use optJSONObject
JSONObject author = jsonArray.optJSONObject(i).optJSONObject("author");
// use optString , it did not return null
String profile_photo = author.optString("profile_photo");
String primary_photo = jsonArray.optJSONObject(i).optString("primary_photo");
}
} catch (JSONException e) {
e.printStackTrace();
}
Gson
JsonArray jsonElements = new JsonParser().parse(response).getAsJsonArray();
for (int i = 0; i < jsonElements.size(); i++) {
JsonObject jObject = jsonElements.get(i).getAsJsonObject();
// edited here
String primary_photo = jObject.get("primary_photo").getAsString();
JsonObject author = jObject.getAsJsonObject("author");
String profile_photo = author.get("profile_photo").getAsString();
}
I think the Problem is, that your JSON response contains an Array. You have to create an JSONArray from the response-string and than iterate about it to get your values. Or if this array always contains one object:
JSONArray jsonArray = new JSONArray(response);
JSONObject jsonObject = jsonArray.getJSONObject(0);
Try this,
try {
JSONArray jsonArray = new JSONArray(response);
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject author = jsonArray.get(i).getJSONObject"author");
String profile_photo = author.getString("author");
}
} catch (JSONException e) {
e.printStackTrace();
}
Try this:
try {
JSONArray jarr=new JSONArray(response); // response is whole json response
for (int i=0;i<jarr.length();i++){
JSONObject jobj=jarr.getJSONObject(i);
String primary_photo=jobj.getString("primary_photo");
}
} catch (JSONException e) {
e.printStackTrace();
}
I am having a JSON string (jsonString):
["[{"Name":"name.pdf","ValueDate":"2016-08-30T22:00:00+0000"}]"]
jsonString is an array and I have to retrieve Name elements from it
I am using below code:
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
System.out.println("jsonString"+ jsonString);
JSONObject jsonObj = new JSONObject();
JSONArray lineItems = jsonObj.getJSONArray(jsonString);
for (Object o : lineItems) {
JSONObject jsonLineItem = (JSONObject) o;
String name = jsonLineItem.getString("Name");
String valueDate = jsonLineItem.getString("ValueDate");
}
But I am getting below error:
net.sf.json.JSONException: JSONObject["[\"[{\"Name\":\"name.pdf\",\"ValueDate\":\"2016-08-30T22:00:00+0000\"}]\"]"] is not a JSONArray.
at net.sf.json.JSONObject.getJSONArray(JSONObject.java:2038) ~[json-lib-2.4.jar:na]
Can anybody help me in this?
Update:
I used JSONArray lineItems = JSONArray.fromObject(jsonString); to come over above error suggested by qxz and used below code to loop through JSONArray
JSONArray lineItems = JSONArray.fromObject(listDocToSendJson);
for (int i = 0; i < lineItems.size(); i++) {
JSONObject jsonObj = lineItems.getJSONObject(i);
String name = jsonObj.getString("Name");
String valueDate = jsonObj.getString("ValueDate");
}
or
for (Object object : lineItems) {
JSONObject jsonStr = (JSONObject)JSONSerializer.toJSON(object);
System.out.println(" name is --"+jsonStr.get("Name"));
System.out.println(" value is ---"+jsonStr.get("ValueDate"));
}
Both are giving errors
net.sf.json.JSONException: JSONArray[0] is not a JSONObject.
java.lang.ClassCastException: net.sf.json.JSONArray cannot be cast to net.sf.json.JSONObject
Please suggest how I can fix this.
To convert a JSON array in a string to a JSONArray, use JSONArray.fromObject:
JSONArray lineItems = JSONArray.fromObject(jsonString); // converts String to JSONArray
for (Object o : lineItems) {
...
}
JSONObject.getJSONArray is for retrieving a given key of a JSON object as an array.
["[{"Name":"name.pdf","ValueDate":"2016-08-30T22:00:00+0000"}]"]
The string does not comply to JSON syntax.
Remove leading [" and trailing "] first then it will be looking like correct JSON array.
This is not valid
["[{"Name":"name.pdf","ValueDate":"2016-08-30T22:00:00+0000"}]"]
but this one is valid
[[{"Name":"name.pdf","ValueDate":"2016-08-30T22:00:00+0000"}]]
The quote ruins the validy of the String. And inorder to parse it you need to loop twice.
JSONArray lineItems = new JSONArray(listDocToSendJson);
for (int i = 0; i < lineItems.size(); i++) {
JSONArray jsonArr = lineItems.getJSONArray(i);
for (int x = 0; x < jsonArr.size(); x++) {
JSONObject jsonObj = lineItems.getJSONObject(i);
String name = jsonObj.getString("Name");
String valueDate = jsonObj.getString("ValueDate");
}
}
}
Try this it should work .. just to add your json string had a problem i have corrected that as well it should as
[{"Name":"name.pdf","ValueDate":"2016-08-30T22:00:00+0000"}]
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
public class JSONTest {
public static void main(String[] args) {
String jsonString ="[{\"Name\":\"name.pdf\",\"ValueDate\":\"2016-08-30T22:00:00+0000\"}]";
System.out.println("jsonString" + jsonString);
try {
JSONArray jsonArray = new JSONArray(jsonString);
for (int i=0;i<jsonArray.length();i++) {
JSONObject jsonObj = jsonArray.getJSONObject(i);
String name = jsonObj.getString("Name");
String valueDate = jsonObj.getString("ValueDate");
System.out.println("Name : "+name + "ValueDate : "+valueDate);
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
Finally I am able to retrieve elements from JSON string looking like this
["[{\"Name\":\"name.pdf\",\"ValueDate\":\"2016-08-30T22:00:00+0000\"}]"]
I used json.jar
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
jsonStringList = jsonStringList.substring(2, jsonStringList.length()-2); //removed brackets and double quotes
jsonStringList = jsonStringList.replaceAll("\\\\", ""); //remove extra backslashes
System.out.println("jsonStringList "+jsonStringList); //valid json //[{"Name":"name.pdf","ValueDate":"2016-08-30T22:00:00+0000"}]
try {
JSONArray jsonArray = new JSONArray(jsonStringList);
for (int i=0;i<jsonArray.length();i++) {
JSONObject jsonObj = jsonArray.getJSONObject(i);
String name = jsonObj.getString("Name");
String valueDate = jsonObj.getString("ValueDate");
System.out.println("Name : "+name + "ValueDate : "+valueDate);
}
Thank you all for great help. :)
I have a webservice which returns a JSON array in this format:
[{"imageid":"3","userid":"1","imagepath":"SLDFJNDSKJFN","filterid":"1","dateadded":"2014-05-06 21:20:18.920257","public":"t"},
{"imageid":"4","userid":"1","imagepath":"dsfkjsdkfjnkjdfsn","filterid":"1","dateadded":"2014-05-06 21:43:37.642748","public":"t"}]
I need to get all the attributes seperately? How would I do this?
I know how to do it with JSONObject if there is just 1 thing being returned, but how does it work when multiple items are returned?
Thanks
try {
JSONArray jArray = new JSONArray(jsonString);
String s = new String();
for (int i = 0; i < jArray.length(); i++) {
s = jArray.getJSONObject(i).getString("imageid").toString();
s = jArray.getJSONObject(i).getString("userid").toString();
}
} catch (JSONException je) {
}
Create an Object class with all variables, create a List for this Object, add all objects in your JSONArray to the list, use the one you need.
List<YourObject> objList = new ArrayList<YourObject>();
JSONArray a = new JSONArray(response);
int size = a.length();
for (int i=0 ; i<size ; i++){
JSONObject aa = a.getJSONObject(i);
String id = aa.getString("imageid");
String userid = aa.getString("userid");
String imagepath = aa.getString("imagepath");
String filterid = aa.getString("filterid");
String dateadded = aa.getString("dateadded");
String publicText = aa.getString("public");
YourObject obj = new YourObject(id,userid,imagepath,filterid,dateadded,publicText);
objList.add(obj);
}
So what you are having here is some JSON objects inside a JSON array.
What you want to do is this:
JSONArray array = ...;
for (int i = 0; i < array.length(); i++) {
JSONObject o = array.getJSONObject(i);
// Extract whatever you want from the JSON object.
}
I hope it helped.
You can use JSONArray to parse array of JSON response.
private void parseJsonArray(String response) {
try {
JSONArray array = new JSONArray(response);
for(int i=0;i<array.length();i++){
JSONObject jsonObject = array.getJSONObject(i);
String ImageId = jsonObject.getString("imageid");
Log.v("JSON Parser", "ImageId: "+ImageId);
}
} catch (Exception e) {
e.printStackTrace();
}
}
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");
}