I'm currently working on an Android application that gets a JSON response from a website called CloudMine. Their responses are typically in this format:
{
"success": {
"key1": { "field": "value1" },
"key2": { "field1": "value1", "field2": "value2" }
},
"errors": {
"key3": { "code": 404, "message": "Not Found" }
}
}
I currently want to loop through all the objects in the "success" object so I can access the different fields in each object. However, I've only been taught how to use the JsonParser from the gson API. The closest I got was using the names() method on the success object but Eclipse yelled at me because the method is undefined for this type.
I appreciate all the help that anyone can give me.
Thanks!
This worked for me:
JsonObject myJsonObject = new Gson().fromJson(myJsonString, JsonObject.class);
for (Map.Entry<String, JsonElement> entry : myJsonObject.entrySet()) {
JsonObject entryObj = entry.getValue().getAsJsonObject();
}
Based on the accepted answer to this question, although I've altered it for my use case:
Iterate over JsonObject properties
Here's a very simple code that would iterate over objects in 'success':
JSONObject json = new JSONObject(responseString);
JSONObject success = json.getJSONObject("success");
JSONObject one;
for(Iterator it=success.keys(); it.hasNext(); ) {
one = success.getJSONObject((String)it.next());
//deal with the next object inside your 'success'
}
Related
I am calling a REST API using the android app, the results of the POST method API is as follows:
{
"Items": {
"ap_id": "37",
"ap_time_from": "14:28",
"ap_time_to": "16:28",
"patient_id": "153",
"patient_name": "Nikhil",
"patient_email": "a#a.com",
"patient_location": "abc"
} }
Converting it into readable data using:
JSONObject jsonObject = new JSONObject(response);
JSONArray jsonArray = jsonObject.getJSONArray("Items");
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject object = jsonArray.getJSONObject(i);
DoctorModel doctorModel1 = new DoctorModel();
doctorModel1.setApp_id(object.getString("ap_id"));
doctorModel1.setStart_timing(object.getString("ap_time_from"));
doctorModel1.setEnd_timing(object.getString("ap_time_to"));
doctorModel1.setUser_id(object.getString("patient_id"));
doctorModel1.setUser_name(object.getString("patient_name"));
doctorModel1.setUser_mail(object.getString("patient_email"));
doctorModel1.setLocation(object.getString("patient_location"));
doctorModelList.add(doctorModel1); }
Now when I am trying to convert it so that I can display the results in a recycler view I am getting the following error:
org.json.JSONException: Value
{"ap_id":"37","ap_time_from":"14:28","ap_time_to":"16:28","patient_id":"153","patient_name":"Nikhil","patient_email":"a#a.com","patient_location":"abc"}
at Items of type org.json.JSONObject cannot be converted to JSONArray
I have been using the same way of converting the JSON Object data into JSON Array, not sure where I am going wrong. Any help would be appreciated, thanks!
You need to have an array as an object inside Items, as follows :
{
"Items":
[
{
"ap_id": "37",
"ap_time_from": "14:28",
"ap_time_to": "16:28",
"patient_id": "153",
"patient_name": "Nikhil",
"patient_email": "a#a.com",
"patient_location": "abc"
}
]
}
Else, change your code to support single object instead of an array
JSONObject jsonObject = new JSONObject(response);
JSONArray object = jsonObject.JSONObject("Items");
In the current response, the value of Items has a JSON object, not a JSON array. That's why this exception happens. To convert this response to data model then you can use this:
JSONObject jsonObject = new JSONObject(response);
JSONArray object = jsonObject.JSONObject("Items");
DoctorModel doctorModel1 = new DoctorModel();
doctorModel1.setApp_id(object.getString("ap_id"));
doctorModel1.setStart_timing(object.getString("ap_time_from"));
doctorModel1.setEnd_timing(object.getString("ap_time_to"));
doctorModel1.setUser_id(object.getString("patient_id"));
doctorModel1.setUser_name(object.getString("patient_name"));
doctorModel1.setUser_mail(object.getString("patient_email"));
doctorModel1.setLocation(object.getString("patient_location"));
doctorModelList.add(doctorModel1);
Or if you want to get the array from json then the JSON will look like this:
{
"Items":
[
{
"ap_id": "37",
"ap_time_from": "14:28",
"ap_time_to": "16:28",
"patient_id": "153",
"patient_name": "Nikhil",
"patient_email": "a#a.com",
"patient_location": "abc"
}
]
}
Hope you understand the isse.
JSONArray jsonArray = jsonObject.getJSONArray("Items"); // this line getting exception because you are trying to convert JSONObject("Items") into JSONArray.
you have to make some changes in the response: 1. If you want to return "Items" as Array in Response.
{
"Items": [
{
"ap_id": "37",
"ap_time_from": "14:28",
"ap_time_to": "16:28",
"patient_id": "153",
"patient_name": "Nikhil",
"patient_email": "a#a.com",
"patient_location": "abc"
}
]
}
If you want to return "Items" like an object in Response then you have to change in code like this
JSONObject jsonObject = new JSONObject(response);
JSONObject jsonObjectItem = jsonObject.getJSONObject("Items");
But in the second case, you can not get the result in the form of an array.
I have already checked other posts of Stack Overflow regarding Json data parsing but did not find the solution to parse inner Json int objects.
I am getting the following response from a web service.
{
"counter":[
{
"1":[
{
"message":"28",
"events":0,
"shared_files":"8"
}
],
"2":[
{
"message":"39",
"events":"4",
"shared_files":"7"
}
]
.....
"n":[
{
"message":"39",
"events":"4",
"shared_files":"7"
}
]
}
]
}
Where "1", "2" and "n" are ids and json object size changes according to the data. I am able to parse the above response till JsonObect using following code:
JsonArray jsonArray = GetJson_.getArray(response, "counter");
if (jsonArray != null) {
JsonObject object = jsonArray.get(0).getAsJsonObject();
}
and my jsonObject now looks like
{
"1":[
{
"message":"28",
"events":0,
"shared_files":"8"
}
],
"2":[
{
"message":"39",
"events":"4",
"shared_files":"7"
}
]
.....
"n":[
{
"message":"39",
"events":"4",
"shared_files":"7"
}
]
}
But I am stuck at how to parse the JsonObject which is dynamic.
Please help.Thanks in advance.
hey you may use HashMap<> for parse dynamic key response for this check this link, other way you may use Iterator which i done below :
JSONObject jsonObject= m_jArry.getJSONObject(0);
Log.e("ad","--------"+jsonObject.toString());
Iterator keys = jsonObject.keys();
while(keys.hasNext()) {
// loop to get the dynamic key
String currentDynamicKey = (String)keys.next();
// get the value of the dynamic key
JSONObject currentDynamicValue = jsonObject.getJSONObject(currentDynamicKey);
// do something here with the value...
}
Hope this will helpful to you.
I try to save properties in a Couchbase-document in Android.
The properties hold a JSONArray with several JSONObjects.
When I do document.putproperties(myproperties) a couchbaseliteexception with state 400 and the message "bad or missing json" is thrown".
So the JSONArray looks like:
"some_prop" -> "[
{
"content":"someContent",
"key2":"",
"key3":"",
"key4":"",
"month":8,
"day":3,
"key5":115
},
{
"content":"Some other content",
"key2":"something",
"key3":"",
"key4":"",
"month":8,
"day":3,
"key5":115
}]"
Can anyone tell me whats the problem with this JSON?
EDIT:
the JSONArray with the corresponding key is saved in a hashmap like it is explained in:
http://developer.couchbase.com/mobile/develop/guides/couchbase-lite/native-api/document/index.html
EDIT 2:
The Method where the update is executed and the JSONArray is filled:
private void updateDoc(ArrayList<MyObject> objects) {
Document document = getDocument();
// Update the document with more data
Map<String, Object> updatedProperties = new HashMap<>();
JSONArray objectArray = new JSONArray();
//fill array with data
for(MyObject element : objects) {
JSONObject jsonObjects = element.toJSONObject();
if(jsonObjects != null) {
objectArray.put(jsonObjects);
}
}
//set data to property map
updatedProperties.put(MYOBJECT_PROP_IDENTIFIER, objectArray);
try {
// Save properties to the Couchbase local Couchbase Lite DB
document.putProperties(updatedProperties);
} catch (CouchbaseLiteException e) {
}
}
Not sure if this is what you're looking for,
You can also use something like http://jsonlint.com to verify your son
{
"some_prop": [
{
"content": "someContent",
"key2": "",
"key3": "",
"key4": "",
"month": 8,
"day": 3,
"key5": 115
},
{
"content": "Some other content",
"key2": "something",
"key3": "",
"key4": "",
"month": 8,
"day": 3,
"key5": 115
}
]
}
Finally I found a solution to the problem:
I don't use JSONObject or JSONArray anymore but save my data in ArrayList and put each element directly into the database. so i don't have an Array with all the elements which but a lot of single elements direktly in the document. To accesss them later I save also the number of elements in the DB. Each element has the index as a prefix so it can be identified later on.
That's not quite a nice way but it works..
So I have a json response from web service like this
{
error: false
types: [2]
-0: {
card_type_id: 5
category: "Food & Beverages"
}
-1: {
card_type_id: 8
category: "Entertaiment"
}
}
what I want to do is to get the number inside json array "types" and use it to looping to set the value of arraylist that will be use in listview, but my code seems and cannot get the json array length, this is my code
JSONObject obj = new JSONObject(response);
if(!obj.getBoolean("error")){
JSONArray types = obj.getJSONArray("types");
for(int i=0; i<types.length();i++)
{
JSONObject a = types.getJSONObject(i);
int ct_id = a.getInt("card_type_id");
String category = a.getString("category");
CardType ct = new CardType();
ct.setTypeId(_ct_id);
ct.setTypeCategory(_category);
categoryArray.add(ct);
}
}
Can anyone help me? Thanks before
This is what your JSON response probably should look like (note also that keys and string values should be sorrounded by double-quotes):
{
"error": false,
"types": [
{
"card_type_id": 5,
"category": "Food & Beverages"
},
{
"card_type_id": 8,
"category": "Entertaiment"
}
]
}
The JSONArray "types" in this example has a length (types.length()) of 2. Now you can implement your for-loop and should get the expected results.
actually it's just my fault to see the json from advanced rest client, i use the json menu and the app automatically correct the json and become invalid, after i change to raw menu i can see the actual json and correct the code
Here is my JSON object and i want to parse it in android project
{
"second": {
"versionInfo": "0.20.3-dev",
"compileDate": "Mon Mar 12 17:39:23 IST 2012",
"compileUser": "suraj",
"trackname": "tracker_localhost:localhost/127.0.0.1:48418"
},
"href": {
"versionInfo": "null",
"compileDate": "null",
"compileUser": "null",
"trackname": "null"
},
"first": {
"key": "['trackname','versionInfo','compileDate','compileUser']"
}
}
How to compile?
i want to first extract attributes of 'first' and using the attributes and then to extract parameters of 'second' using attributes of 'first'.
Basically it is done like that:
JSONObject jobj = new JSONObject(theString);
JSONObject first = jobj.getJSONObject("first");
JSONObject second = jobj.getJSONObject("second");
If you want more, take a look at the documentation of JSON classes for android.
Edit
Regarding the extraction of the array (in first->key):
String jStr = first.getString("key");
JSONArray jArr = new JSONArray(jStr);