Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android parse JSONObject

I've got a little problem with parsing json into my android app.

This is how my json file looks like:

{
"internalName": "jerry91",
"dataVersion": 0,
"name": "Domin91",
"profileIconId": 578,
"revisionId": 0,
}

As You can see this structure is a little bit weird. I dont know how to read that data in my app. As I noticed those are all Objects not arrays :/

like image 931
Dominik Avatar asked Nov 02 '13 20:11

Dominik


2 Answers

You can always use good old json.org lib. In your Java code :

  • First read your json file content into String;
  • Then parse it into JSONObject:

    JSONObject myJson = new JSONObject(myJsonString);
    // use myJson as needed, for example 
    String name = myJson.optString("name");
    int profileIconId = myJson.optInt("profileIconId");
    // etc
    
like image 127
kiruwka Avatar answered Oct 12 '22 14:10

kiruwka


to know if string is JSONArray or JSONObject

JSONArray String is like this

[{
"internalName": "blaaa",
"dataVersion": 0,
"name": "Domin91",
"profileIconId": 578,
"revisionId": 0,
},
{
"internalName": "blooo",
"dataVersion": 0,
"name": "Domin91",
"profileIconId": 578,
"revisionId": 0,
}]

and this String as a JSONOject

{
"internalName": "domin91",
"dataVersion": 0,
"name": "Domin91",
"profileIconId": 578,
"revisionId": 0,
} 

but how to call elements from JSONArray and JSONObject ?

JSNOObject info called like this

first fill object with data

JSONObject object = new JSONObject(
"{
\"internalName\": \"domin91\",
\"dataVersion\": 0,
\"name\": \"Domin91\",
\"profileIconId\": 578,
\"revisionId\": 0,
}"
);

now lets call information from object

String myusername = object.getString("internalName");
int dataVersion   = object.getInt("dataVersion");

If you want to call information from JSONArray you must know what is the object position number or you have to loop JSONArray to get the information for example

looping array

for ( int i = 0; i < jsonarray.length() ; i++)
{
   //this object inside array you can do whatever you want   
   JSONObject object = jsonarray.getJSONObject(i);
}

if i know the object position inside JSONArray ill call it like this

//0 mean first object inside array
 JSONObject object = jsonarray.getJSONObject(0);
like image 28
Noob Avatar answered Oct 12 '22 15:10

Noob