0

This is my json-string:

[
    {
        "id": 1,
        "ip": "192.168.0.22",
        "folderName": "gpio1_pg3"
    },
    {
        "id": 2,
        "ip": "192.168.0.22",
        "folderName": "gpio2_pb16"
    }
]

I want to iterate about the array, because I will create an special object for each array member.

This is the way how I get the json string from an http url.

BufferedReader bufferedReader = 
         new BufferedReader(new InputStreamReader(inputStreams, Charset.forName("UTF-8")));

String jsonText = readAll(bufferedReader);

Could you give me an example how I can get an Array of all json-elements. One array-element have to contain the id, ip, and folderName.

Tobb
  • 11,850
  • 6
  • 52
  • 77
Andreas Fritsch
  • 244
  • 3
  • 6
  • 19

2 Answers2

4

Jackson or GSON are popular libraries for converting JSON strings to objects or maps.

Jackson example:

String json = "[{\"foo\": \"bar\"},{\"foo\": \"biz\"}]";
JsonFactory f = new JsonFactory();
JsonParser jp = f.createJsonParser(json);
// advance stream to START_ARRAY first:
jp.nextToken();
// and then each time, advance to opening START_OBJECT
while (jp.nextToken() == JsonToken.START_OBJECT)) {
    Foo foobar = mapper.readValue(jp, Foo.class);
    // process
    // after binding, stream points to closing END_OBJECT
}

public class Foo {
    public String foo;
}
MarkHu
  • 1,694
  • 16
  • 29
Yusuf K.
  • 4,195
  • 1
  • 33
  • 69
1

Try,

JSONArray array = new JSONArray(jsonStr); 

for(int i=0; i<array.length(); i++){
    JSONObject jsonObj = array.getJSONObject(i);
    System.out.println(jsonObj.getString("id"));
    System.out.println(jsonObj.getString("ip"));
    System.out.println(jsonObj.getString("folderName"));
}

OR you can try with Google's JSON library (google-gson)

JsonParser jsonParser = new JsonParser();
JsonElement element = jsonParser.parse(your json string);
Rakesh KR
  • 6,357
  • 5
  • 40
  • 55