I would like to parse Java String containing json into some Java container/collection.
I have no problem with string A which contain something like below:
{"id":"0bda5158-a533-498a-8657-79aec0c3fb65","name":"Andrzej","email":"test@gmail.com"}
Simple json ==> string <-> string. The problem is when the string B contains something like below (array of json):
[{"id":"0bda5158-a533-498a-8657-79aec0c3fb65","name":"Andrzej","email":"test@gmail.com"}]
This is the code which I used to parse:
private static class TestResponse {
public final String body;
public final int status;
public TestResponse(int status, String body) {
this.status = status;
this.body = body;
}
public Map<String, String> json() {
return new Gson().fromJson(body, HashMap.class);
}
}
Request method looks like:
private TestResponse request(String method, String path) {
try {
URL url = new URL("http://localhost:4567" + path);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod(method);
connection.setDoOutput(true);
connection.connect();
String body = IOUtils.toString(connection.getInputStream());
return new TestResponse(connection.getResponseCode(), body);
} catch (IOException e) {
e.printStackTrace();
fail("Sending request failed: " + e.getMessage());
return null;
}
}
Everything work for the first string A. I have been doing something like below (simple Map):
TestResponse res = request("PUT", "/user/create?name=Andrzej&email=test@gmail.com");
Map<String, String> json = res.json();
The problem is with the string B - there is an array of json. There I cannot use simple Map. I do not know how to solve it. Please help me and thank you in advance.