Sunday 15 December 2019

How to read json string in java?




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.



Answer



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;
}


No comments:

Post a Comment

php - file_get_contents shows unexpected output while reading a file

I want to output an inline jpg image as a base64 encoded string, however when I do this : $contents = file_get_contents($filename); print &q...