Monu Mittal
Monu Mittal

Reputation: 95

how to iterate json String

I have an array of JSON strings like:

[{
"id":"BirthDate",
"field":"BirthDate",
"type":"date",
"input":"text",
"operator":"equal",
"value":"2016/04/07"
}]

I want to be able to iterate this array and want to get its id, field, value in Java

Using the below code I got an exception "json object must begin with {"

String rules=helper.getRules();
    System.out.println("====Rulses=====:"+rules);
      try {
           JSONObject obj = new JSONObject(rules);
           System.out.println("====obj===="+obj);
          // boolean error = obj.getBoolean("error");
           String id = obj.getString("id");
           System.out.println("===id is===: "+id);
      } catch (JSONException e){
          e.printStackTrace();
      }

Upvotes: 2

Views: 13745

Answers (2)

Guillaume Barré
Guillaume Barré

Reputation: 4218

Try this parsing your rulesinto a JSONArray:

String rules = "[{\"id\":\"BirthDate\",\"field\":\"BirthDate\",\"type\":\"date\",\"input\":\"text\",\"operator\":\"equal\",\"value\":\"2016/04/07\"}]";

try {
    JSONArray obj = new JSONArray(rules); // parse the array
    for(int i = 0; i < obj.length(); i++){ // iterate over the array
        JSONObject o = obj.getJSONObject(i);
        String id = o.getString("id");
        System.out.println("===id is===: " + id);
    }
} catch (JSONException e){
    e.printStackTrace();
}

In the JSON you gave as example you just have one element in your array.

Upvotes: 0

Sandeep Sukhija
Sandeep Sukhija

Reputation: 1176

You should instead create a JSONArray from the String and then iterate over the array. Modify your code as

String rules=helper.getRules();
System.out.println("====Rulses=====:"+rules);
try {
    // create the json array from String rules
    JSONArray jsonRules = new JSONArray(rules);
    // iterate over the rules 
    for (int i=0; i<jsonRules.length();i++){
        JSONObject obj = jsonRules.get(i);
        System.out.println("====obj===="+obj);

        String id = obj.getString("id");
        System.out.println("===id is===: "+id);
    }
} catch (JSONException e){
    e.printStackTrace();
}

Upvotes: 3

Related Questions