Failed to Parse JSON Response - android

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();
}

Related

How to get array number JSON android

I have JSON :
{"elements":[{"id":5,"name":"Mathematics","shortName":"math","links":{"courses":[15,30,46,47]}}]}
My code :
List<NameValuePair> params = new ArrayList<NameValuePair>();
// getting JSON string from URL
JSONObject json = jParser.makeHttpRequest(url_all_products, "GET", params);
// Check your log cat for JSON reponse
//Log.d("All Products: ", json.toString());
try {
products = json.getJSONArray("elements");
for (int i = 0; i < products.length(); i++) {
JSONObject c = products.getJSONObject(i);
// Storing each json item in variable
int ids = c.getInt(TAG_PID);
String id = String.valueOf(ids);
if (id.compareTo(id_kh) == 0) {
object = c.getJSONObject("links");
JSONArray courses = object.getJSONArray("courses");///???????????
//result = courses.split("[,]");
Toast.makeText(getBaseContext(),"abc",Toast.LENGTH_LONG).show();
break;
}
}
} catch (JSONException e) {
e.printStackTrace();
}
I dont know to get array number after "courses".
I would use HashMaps. Here you have an example (creating Hashmap from a JSON String
) how to get it from a JSON String.
Particularly for the "courses", once you have been parsed until there, I would use a HashMap<String,List<Integer>>
courses is a JSONArray, so you can do like that:
JSONArray coursesArray = linksObject.getJSONArray("courses");
UPDATE:
To get values from coursesArray :
int value = coursesArray.optInt(position);
Almost there. Once you get your
JSONArray courses = object.getJSONArray("courses");
simply iterate over its values:
// you wanted these numbers in an array
// so let's create one, with size being number of elements in
// JSONArray courses
int[] courseIds = new int[courses.length()];
for (int j=0; j<courses.length(); j++) {
// assign current number to the appropriate element in your array of ints
coursesId[j] = courses.getInt(j);
Log.d("TAG", "number: " + number);
}
The above will save these numbers in an array and print them too:
number: 15
number: 30
number: 46
number: 47
Just keep in mind that "courses" key might not exist, the array might be empty etc.

How to parse json response in android which is of the following format

I am trying to parse a json response in android for my android application. I am getting org.json.JSONException. The response is as shown below:
{
id: "12345"
email:"abc#gmail.com"
firstName:"abcd"
lastName:"efgh"
userName:"abc123"
}
I am trying to parse the response as shown below:
if (response != null) {
try {
//JSONObject jsonObj = new JSONObject(text);
// Getting JSON Array node
JSONArray contacts = new JSONArray(response.toString());
// looping through All Contacts
for (int i = 0; i < contacts.length(); i++) {
JSONObject c = contacts.getJSONObject(i);
id = c.getString("_id");
email = c.getString("email");
firstName = c.getString("firstName");
lastName = c.getString("lastName");
userName = c.getString("userName");
}
} catch (JSONException e) {
e.printStackTrace();
}
Can any one let me know what mistake am I doing in parsing the response. All suggestions are welcome.
Simply replace this you are using "_id" instead of "id"
id = c.getString("id");
email = c.getString("email");
firstName = c.getString("firstName");
lastName = c.getString("lastName");
userName = c.getString("userName");
Change this id = c.getString("_id"); to id = c.getString("id");
in the future, you may show error in logcat when parsing like this:
catch (JSONException e) {
e.printStackTrace();
Log.e("TAG", e.getMessage());
}
There are two things I can think of , first of all you should get to know that what are [] , {} . The square brackets are arrays in json and curly demonstrate the object , so I think you are casting it wrong
1>
JSONArray contacts = new JSONArray(response.toString()); "this is culprit"
You should change it to
JSONObject. Use JSONObject in place of JSONArray
and Secondly
2> change this key id = c.getString("_id");to
id = c.getString("id");
Make sure You are getting and writing spellings of all keys right else it would generate exception.

data from a jsonobject in android

The below is called from a string url and returns a json object which has an json array inside, but something else is not working, can anyone show me how to access the data inside?
{"data":[{"8196":{"booking_id":"8150","client_id":"107","venue_id":null}}]
String jsonStr = "{\"data\":[{\"8196\":{\"booking_id\": \"8150\",\"client_id\": \"107\",\"venue_id\": null}}]}";
try {
JSONObject json = new JSONObject(jsonStr);
JSONArray array = json.getJSONArray("data");
for (int i = 0; i < array.length(); i++) {
JSONObject o = array.getJSONObject(i);
Iterator it = o.keys();
while (it.hasNext()) {
String name = (String) it.next();
o = o.getJSONObject(name);
int bookingId = o.getInt("booking_id");
int clientId = o.getInt("client_id");
int venueId = o.optInt("venue_id");
Log.v("TEST", String.format("Booking ID: %s -- Client ID: %s -- Venue ID: %s", bookingId, clientId, venueId));
}
}
} catch (JSONException e) {
e.printStackTrace();
}
I guess this is what you'll want. By the way, the JSON you posted is malformed. It's missing a } in the end.
You first need to decode the JSON string. The JSON sting you got in return is actually a serialized version of a JSON object.
You need to decode that string into a native Java Object.
There are a number of methods to this in Java. You can start by checking out the Java section at json.org.
I think the problem is that the value of key venue_id is null. You can replace null value with empty string(""), try it.

JSON parsing returning a null value

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.

Json Without Key to Parse in Android

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().

Categories

Resources