Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to iterate JSONArray in java

I would like to extract the values from JSONArray. JSONArray has N number of rows and columns.

        ObjectMapper mapper = new ObjectMapper();
        DynamicForm dynamicForm = new DynamicForm();
        dynamicForm = dynamicForm.bindFromRequest();
        Dynamic dynamic = dynamicForm.get(); 
        //List<OneModel> list = new ArrayList<OneModel>();
        //List iterate=new ArrayList();

        String data = dynamic.getData().get("content").toString();
        try {
            JSONArray jsonArray = new JSONArray(data);
            for (int i = 0; i < jsonArray.length(); i++) {
                System.out.println(jsonArray.get(i));
        } }catch (JSONException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }   

Its resulting as follows.

["1001432","05-KALENJI-P1229","KALENJI","2","2014-11-09 09:37:14.379482",""],
["1001432","05-KALENJI-P1228","KALENJI","1","2014-11-09 09:37:14.379482",""],
["1001432","05-KALENJI-P1227","KALENJI","5","2014-11-09 09:37:14.379482",""]

I would like to extract one by one values and assign it to variable. for example 1001432,05-KALENJI-P1229,KALENJI,2,2014-11-09 09:37:14.379482. So that i can process each values. Please any one help me in the same

like image 424
Kathirvel Appusamy Avatar asked Jul 20 '26 09:07

Kathirvel Appusamy


2 Answers

You can use the following code:

//put your json in the string variable "data"

JSONArray jsonArray=new JSONArray(data);
            if(jsonArray!=null && jsonArray.length()>0){
                for (int i = 0; i < jsonArray.length(); i++) {
                    JSONArray childJsonArray=jsonArray.optJSONArray(i);
                    if(childJsonArray!=null && childJsonArray.length()>0){
                        for (int j = 0; j < childJsonArray.length(); j++) {
                            System.out.println(childJsonArray.optString(j));
                        }
                    }
                }
            }
like image 170
Krunal Indrodiya Avatar answered Jul 22 '26 01:07

Krunal Indrodiya


It looks like the JSON array is 2 dimensional. Try this:

JSONArray outerArray = new JSONArray(data);
for (int i = 0; i < outerArray.length(); i++) {
    JSONArray innerArray = outerArray.getJSONArray(i);

    for (int j = 0; j < outerArray.length(); j++) {
        System.out.println(innerArray.get(j));
    }
}
like image 24
jmn Avatar answered Jul 22 '26 01:07

jmn



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!