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
Related
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'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'
}
I am parsing some json in an app and I have come across arrays that sometimes have information in it:
{
"output": [
{
"id": "1521",
"name": "Apples",
}
]
}
and sometimes has nothing. e.g
{
"output": [
[]
]
}
I was parsing it by
JSONArray output = c.getJSONArray("output");
int outputLength = output.length();
for (int q = 0; q < outputLength; q++)
{
JSONObject d = outputs.getJSONObject(q);
id[q] = d.getInt("id");
name[q] = d.getString("name");
}
but when it gets to the empty array it crashes.
I get the following error then:
01-19 01:08:00.237: W/System.err(17627): org.json.JSONException: Value [] at 0 of type org.json.JSONArray cannot be converted to JSONObject
it crashes because it's trying to convert the jsonarray into an object and you can't do that so I tried getting the first array in output with:
JSONArray add = output.getJSONArray(0);
but that will crash as well because in the first output it's an object in it and not an array.
I don't have access or control over the json feed and I'm stuck at the moment as to how to parse the result.
The real answer is: "Fix whatever is generating that horrible JSON".
If that's not an option you're going to have to figure out exactly what you have before trying to access it. The JSONArray.optJSONObject() method can help with this; it returns null if the specified index doesn't contain a JSONObject:
JSONArray output = c.getJSONArray("output");
for (int q = 0; q < outputLength; q++)
{
JSONObject d = output.optJSONObject(q);
if (d != null)
{
id[q] = d.getInt("id");
name[q] = d.getString("name");
}
}
Because you're parsing everything in the enclosing JSONArray as aJSONObject, all the entries would have to be formatted that way. For that to work, your source string would have to look like this:
[
{
"output": [
{
"id": "1521",
"name": "Apples"
}
]
},
{
"output": [
[]
]
}
]
Everything in the top-levelJSONArray is now a JSONObject and can be parsed accordingly. What's inside of those objects is your business (empty arrays are OK). A good resource for checking if a given JSON string is valid is this website.
I am trying to read a list from JSON format into Android Java.
I can read children using getJSONarray(). But unable to read values of message or email.
Seems getJSONarray() doesnt work for what i want.
Yes, i am using getJSONObject on children to extract message. But how do i extract individual values after getting message array?
{
"children": [{
"message": ["message1","message2","message3"],
"email": ["email1",
"email2"]
}, {
"message": ["message1", "message2", "message3"],
"email": ["email1", "email2"]
}]
}
I know how to extract from:
{
"children": [{
"message1": "message___1"
"message2": "message___2"
"message3": "message___3"
}]
}
But not when it is all in a list.
What you need to do once you've got the JSONArray of "children" is to then extract the individual JSONObjects one by one like so:
for (int counter = 0; counter < childArray.length(); counter++) {
//Get the next item
JSONObject nextobj = childArray.getJSONObject(counter);
Then you can extract your message and email arrays from your nextobj variable. This is because each "message" and "email" is not directly accessible from your "children" JSONArray, they're wrapped up in JSONObjects
try the below code:
for(int i=0; i<childrenArray.length(); i++)
{
JSONObject childObj=childrenArray.getJSONObject(i);
JSONArray messageArray=childObj.getJSONArray("message");
for(int j=0; j<messageArray.length();j++
{
//here get value from messageArray.getString(j) or messageArray.getJSONObject(j), whichever applicable
}
JSONArray emailArray=childObj.getJSONArray("email");
for(int k=0; k<emailArray.length();k++
{
//here get value from emailArray.getString(k) or emailArray.getJSONObject(k), whichever applicable
}
}
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);