Reputation: 227
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
Upvotes: 3
Views: 69861
Reputation: 792
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));
}
}
}
}
Upvotes: 9
Reputation: 564
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));
}
}
Upvotes: 1
Reputation: 3512
Your can iterate over the array via a loop and get your objects like this:
JsonObject home = array.getJsonObject(index); //use index to iterate
String num = home.getString("number"); //make number a static final variable
The "number" is the name for the value, which was originally put in with
.add("number", someString);
Greets.
edit: I recommend to read the docu: Oracle Doc and this, too.
Upvotes: 0