I have the following sample json:
{\"2013-05-30\":{\"available\":\"1\",\"bind\":0,\"info\":\"\",\"notes\":\"\",\"price\":\"\",\"promo\":\"\",\"status\":\"available\"},
\"2013-05-31\":{\"available\":\"1\",\"bind\":0,\"info\":\"\",\"notes\":\"\",\"price\":\"\",\"promo\":\"\",\"status\":\"available\"},
\"2013-06-01\":{\"available\":\"1\",\"bind\":0,\"info\":\"\",\"notes\":\"\",\"price\":\"\",\"promo\":\"\",\"status\":\"available\"}}
I read this into a String and then parse it into a JSONObject, but I need it to be in a JSONArray.
I have tried adding programmatically "[" at the beginning of the string and "]" at the end of it, before I convert it into a JSONArray, and, although it recognizes it as an Array, it still sees it as a single object (I only seem to have JSONArray(0)).
This is how I try to parse the jsonData as an Array:
try{
jArray = new JSONArray(resultString);
for(int i=0;i<jArray.length();i++){
JSONObject json_data = jArray.getJSONObject(i);
Log.i("log_4","Available: "+json_data.getString("available")+
", Bind: "+json_data.getString("bind")+
", Info: "+json_data.getString("info") +
", Notes: "+json_data.getString("notes") +
", Price: "+json_data.getString("price") +
", Promo: "+json_data.getString("promo") +
", Status: "+json_data.getString("status")
);
}
}catch(JSONException e){
Log.e("log_5", "Error parsing data "+e.toString());
}
and here is the version in which I don't add [ and ], therefore parsing it as a JSONObject.
try {
jsonResponse = new JSONObject(resString);
} catch (JSONException e) {
Log.e("log_3", "Error parsing data "+e.toString());
}
How can I separate each day (e.g."2013-05-30") into a different object, with each object having as key the value of the day?
Thanks a lot!
Instead of adding a [ at the begining and a ] at the end, try replacing the first instance of { with [ and the last instance of } with ] and then making a JSONArray out of it.
Related
Assume that I get this JSon Response from webservice:
{
"id":13,
"name":"Alireza",
"required_id":"14",
"all_friends_id_and_name":{
"28":"Hassan",
"21":"Mohammad",
"68":"Ali",
"14":"Taha",
"96":"Darya"
}
}
In this response required_id value specifies that I need a friend name with id 14, so in all_friends_id_and_name object I should get the value of "14" (Taha) and use it in my app.
I'm using retrofit2 and gson libraries.
How to get property of an object which has non-fixed keys?
For Native approach, You can Try with Iterator .
An iterator is an object that enables a programmer to traverse a
container, particularly lists.
"all_friends_id_and_name":{
"28":"Hassan",
"21":"Mohammad",
"68":"Ali",
"14":"Taha",
"96":"Darya"
}
For the above section, Your LOGIC will be
JSONObject jsonData = new JSONObject("Json_response");
Iterator iteratorObj = jsonData .keys();
while (iteratorObj.hasNext())
{
String str_json_Key = (String)iteratorObj.next();
// Print=28,21....96
}
Here is your Json:
{
"id":13,
"name":"Alireza",
"required_id":"14",
"all_friends_id_and_name":{
"28":"Hassan",
"21":"Mohammad",
"68":"Ali",
"14":"Taha",
"96":"Darya"
}
}
Try by doing like this :
try {
JSONObject jsonObject; // it should be your above JsonObject
Iterator<?> keys = jsonObject.keys();
while (keys.hasNext()) {
String key = (String) keys.next();
System.out.println("Mykey: " + key + " value: " + jsonObject.getString(key));
}
} catch (JSONException e) {
e.printStackTrace();
}
My basic JSON data structure is this:
[
{
"data1":"contents of data1",
"data2":"contents of data 2"
},
{
"data1":"contents of data1",
"data2":"contents of data 2"
}
]
I tried using JSONArray myJson = new JSONArray(json);
but it gives me:
org.json.JSONException: Not a primitive array: class org.json.JSONObject
I am retrieving the JSON through:
JSONParser jParser = new JSONParser();
// Getting JSON from URL
JSONObject json = jParser.getJSONFromUrl(url);
And convert it to JSONArray using JSONArray myJson = new JSONArray(json);
Thanks!
Iterate your json without key as follows
try {
JSONArray jsonArray = new JSONArray("[{\"data1\":\"contents of data1\",\"data2\":\"contents of data 2\"},{\"data1\":\"contents of data1\",\"data2\":\"contents of data 2\"}]");
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObject = jsonArray.getJSONObject(i);
Iterator<?> keys = jsonObject.keys();
while (keys.hasNext()) {
String key = (String) keys.next();
System.out.println("Mykey: " + key + " value: " + jsonObject.getString(key));
}
}
} catch (JSONException e) {
e.printStackTrace();
}
The reason of that error might be invalid json.
This is how your data2 key - value pair is
"data2":contents of data 2"
Put the quotes " before contents and use this
"data2":"contents of data 2"
Change all occurences of this error and it should work. Do let me know if it changes anything for you.
In python, If u have json data as
data=[{
"data1":"contents of data1",
"data2":"contents of data 2"
},
{
"data1":"contents of data1",
"data2":"contents of data 2"
}
]
you can access it using:
print "data1:",data[0]["data1"]
I have JSON Response like this.I have tried a lot but unable to parse the Values.
This one is my Actual Response...
{"ResponseCode":"000","ResponseDescription":"Successful","SystemServiceID":["0000"],"SystemServiceName":["Test"],"ProductID":["000"],"ProductName":["Test"],"ProductDescription":["Test product"],"MinimumValue":[10000],"MaximumValue":[500000],"ImageURL":[null],"Country":["AAAA"],"CompanyID":["1"],"CompanyName":["Test"],"FieldLevel":["2"],"FieldInfo":["{\"Field1\":{\"Field Name\":\"Phone Number\",\"Field Type\":\"Number\",\"Validation\":{\"Min\":\"4\",\"Max\":\"8\"}},\"Field2\":{\"Field Name\":\"Email\",\"Field Type\":\"String\",\"Validation\":{\"Regular Expression\":\"abcd\",\"Min Length\":\"10\",\"Max Length\":\"20\"}}}"]}
Out of this i am able to parse all the field expect the below one...
{
"Field1":
{
"Field Name":"Phone Number",
"Field Type":"Number",
"Validation":{"Min":"4","Max":"8"}
},
"Field2":
{
"Field Name":"Email",
"Field Type":"String",
"Validation":{"Regular Expression":"abcd","Min Length":"10","Max Length":"20"}
}
}
I also want to fetch the value of Validation":{"Min":"4","Max":"8"} this field.Like it has max value 4 and min value is 8.
Any Help will be appreciated.
Thanks in Advance ... :)
Here is the code to read Min And Max values
JSONObject parentObject = new JSONObject(Json_String);
JSONObject field1 = parentObject.getJSONObject("Field1");
JSONObject validation = field1.getJSONObject("Validation");
String min = validation.getString("Min");
String max = validation.getString("Max");
Assuming your JSON string is well formed.
Since in your response you are not getting the "\" into JSON so you need to some modifications into that like (update : It seems that replacement not required here)
String json = "{\"Field1\":{\"Field Name\":\"Phone Number\",\"Field Type\":\"Number\",\"Validation\":{\"Min\":\"4\",\"Max\":\"8\"}},\"Field2\":{\"Field Name\":\"Email\",\"Field Type\":\"String\",\"Validation\":{\"Regular Expression\":\"abcd\",\"Min Length\":\"10\",\"Max Length\":\"20\"}}}";
// json.replace("\\", ""); // I verified that parsing works well without replacement too
try {
JSONObject parentObject = new JSONObject(json);
JSONObject field1 = parentObject.getJSONObject("Field1");
JSONObject validation = field1.getJSONObject("Validation");
String min = validation.getString("Min");
String max = validation.getString("Max");
System.out.println("Min ::::::: " + min);
System.out.println("MAx ::::::: " + max);
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
I am trying to parse the response i get from the network database. I am getting only one value i.e. seller id in response. When i try to pass it in JSON Object, somehow the toast after it doesn't execute and the toast after it is not executed.
I know there are many related questions but i can't find whats wrong... please help. Thanks.
try {
JSONArray jArray = new JSONArray(stuff.toString());
Toast.makeText(this, "len: " + jArray.length(), 1000).show(); // length is 1
for (int i = 0; i < jArray.length(); i++) {
Toast.makeText(this, "Arr: " + stuff, 1000).show();
// Arr: [{"seller_id":"5"}]
JSONObject jObject = jArray.getJSONObject(i);
j_id = jObject.getString(stuff);
// not getting executed
Toast.makeText(this, "JSON: " + j_id, 1000).show();
}
} catch (JSONException e) {
e.printStackTrace();
}
Toast.makeText(this, "View: " + j_id, 1000).show(); // j_id is giving null value
This is my json data [{"seller_id":"5"}] i am trying to get the value of seller id (ie 5 here) out of it.
There is a problem in jObject.getString() method args
JSONObject jObject = jArray.getJSONObject(i);
j_id = jObject.getString(stuff);
Your giving the array. It should the name of the object i.e seller_id
so after the modification your code would be j_id = jObject.getString("seller_id");
After the following code:
j_id = jObject.getString(stuff);
add textview.settext(j_id);
and change this textview with your textview name
and if its not working than show your complete json data.
I have this below Json which I'm getting from a .Net Web service:
[["Developer","test","developer#test.com"]]
I checked with jsonlint validator and It shows above json fine.
Because it is not having any key I don't know how to parse it in Android.
Can someone please help me how to parse this json without key.
If it had keys, I would have tried this:
{"first":"somevalue","last":"someothervalue"} // Json response
JSONObject json_obj = new JSONObject(resp); //response is the json array
String first = json_obj.getString("first");
String last = json_obj.getString("last");
String test = "Hello! " + first + " " + last;
Hope someone helps :)
Regards,
Praveen
MY SOLUTION
JSONArray respo = new JSONArray(resp); //resp is Json Array
respo = respo.getJSONArray(0);
String test = respo.getString(2);
test = "Your Email Address is " + test;
in Android (Java) parsing this line looks like:
String jsonString="[[\"Developer\",\"test\",\"developer#test.com\"]]";
try {
JSONArray jsonArray=new JSONArray(jsonString);
JSONArray jsonArray2=jsonArray.getJSONArray(0);
for (int i = 0; i < jsonArray2.length(); i++) {
String valueString=jsonArray2.getString(i);
Log.e("json", i+"="+valueString);
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Use JSONArray instead of JSONObject. Then use the getJSONArray() function to get the array inside the array. After that you can access all values with their index and getString().