ANucool Mittal ANucool Mittal - 5 months ago 12
JSON Question

how to put json string into list in java

I'm getting a

JSON array
in string like

[ { "id":"ca.Primary_Diagnosis_Dt",
"field":"ca.Primary_Diagnosis_Dt",
"type":"date",
"input":"text",
"operator":"not_equal",
"value":"2016/06/07"
},
{ "id":"ca.Clinical_Stage",
"field":"ca.Clinical_Stage",
"type":"integer",
"input":"select",
"operator":"equal",
"value":"I"
}
]


i just want to save the value of id ,operator and value in
LIST
please help

Answer

First create a class to store your values :

class Data{
  String id;
  String operator;
  String value;
}

Then iterate over the json :

    JSONArray jsonArr = new JSONArray("[JSON Stirng]");
    List<Data> dataList = new ArrayList<>();
    for (int i = 0; i < jsonArr.length(); i++) {

        JSONObject jsonObj = jsonArr.getJSONObject(i);
        Data data = new Data();

        data.id = jsonObj.getString("id");
        data.operator = jsonObj.getString("operator");
        data.value = jsonObj.getString("value");

        dataList.add(data);
    }

Now dataList has your data!

P.S. : Use getter/setters in Data class

JAR : http://www.java2s.com/Code/Jar/j/Downloadjavajsonjar.htm

Comments