Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to parse a JSONArray of JSONObjects in JAVA?

I have the following array returned to my JAVA Android application from PHP:

Array ( [0] => Array ( [referral_fullname] => Name 1 [referral_balance] => 500 ) [1] => Array ( [referral_fullname] => Name 2 [referral_balance] => 500 ) );

In Java they above array looks like this:

{"0":{"referral_fullname":"Name 1","referral_balance":"500"},"1":{"referral_fullname":"Name 2","referral_balance":"500"}};

For a simple JSONObject I'm using:

JSONTokener tokener = new JSONTokener(result.toString());
JSONObject finalResult = new JSONObject(tokener);

referral_fullname = finalResult.getString("referral_fullname");

but for an array of objects I don't know!

like image 934
Andrei Stalbe Avatar asked Jan 25 '26 20:01

Andrei Stalbe


2 Answers

String str = your Json-> apply to.String();

    JSONObject jObject  = new JSONObject(str);


    Map<String,String> map = new HashMap<String,String>();
    Iterator iter = jObject.keys();
    while(iter.hasNext()){
        String key = (String)iter.next();
        String value = jObject .getString(key);
        map.put(key,value);
    }
like image 128
Dheeresh Singh Avatar answered Jan 28 '26 08:01

Dheeresh Singh


Your Json Syntax is wrong , JSONArray should be like this :

["0":{"referral_fullname":"Name 1","referral_balance":"500"},"1":{"referral_fullname":"Name 2","referral_balance":"500"}];

and to parse a JsonArray that contains some JSONObject , try this :

//parse the result
            JSONObject jsonResult = null;
            JSONArray arrayResult = null;
            ArrayList<YourObject> listObjects = null;
            try {
                arrayResult = new JSONArray(result);
                if(arrayResult != null) {
                    listObjects = new ArrayList<YourObject>();
                    int lenght = arrayResult.length();
                    for(int i=0; i< lenght; i++) {
                        JSONObject obj = arrayResult.getJSONObject(i);
                        YourObject object = new YourObject(obj);
                        listObjects.add(object);
                    }
                }
            } catch (JSONException e) {
                e.printStackTrace();
            }

And add a constructor in your Class YourObject to convert your Json to an instance :

public YourObject(JSONObject json) {
    if (!json.isNull("referral_fullname"))
        this.referral_fullname = json.optString("referral_fullname", null);
    if (!json.isNull("referral_balance"))
        this.referral_balance = json.optString("referral_balance", null);
}
like image 24
Houcine Avatar answered Jan 28 '26 10:01

Houcine