Basically, I have the JSON file below and I need to read him and add into a List of Objects in Java, Which library should I use in this case? My biggest difficulty is read the Json starting with the array instead of a normal object, and inside the elements of the first array try to read the other array inside.
[
{
"name: "Andrew"
"age": 21,
"parents": [
{
"name": "Joseph",
"age": 18
},
{
"name": "Joseph",
"age": 18
}
]
},
{
"name: "Maria"
"age": 35,
"parents": [
{
"name": "Kassandra",
"age": 16
},
{
"name": "Abigail",
"age": 22
}
]
}
]
CodePudding user response:
Use jackson library. Here is a snippet.
public static void main(final String[] args) throws JsonProcessingException {
final List<Child> children = new ObjectMapper().readValue(
readFromFile("data.json"), new TypeReference<List<Child>>() {
});
System.out.println(children);
}
public static String readFromFile(final String resourcePath) {
final ClassPathResource resource = new ClassPathResource(resourcePath);
try {
final InputStream inputStream = resource.getInputStream();
return readFromInputStream(inputStream);
} catch (final IOException var4) {
return "";
}
}
private static String readFromInputStream(final InputStream inputStream) throws IOException {
final StringBuilder resultStringBuilder = new StringBuilder();
final BufferedReader br = new BufferedReader(new InputStreamReader(inputStream));
Throwable var3 = null;
try {
String line;
try {
while ((line = br.readLine()) != null) {
resultStringBuilder.append(line).append("\n");
}
} catch (final Throwable var12) {
var3 = var12;
throw var12;
}
} finally {
if (br != null) {
if (var3 != null) {
try {
br.close();
} catch (final Throwable var11) {
var3.addSuppressed(var11);
}
} else {
br.close();
}
}
}
return resultStringBuilder.toString();
}
CodePudding user response:
There are lots of API's and libraries are present but I prefer to use org.json
API suggested by json.org
you can also go for GSON library which is one of the best library for serialize and deserialize Java objects to (and from) JSON.
here's the quick demo of reading above JSON with org.json API.
import org.json.JSONObject;
import org.json.JSONArray;
public class HelloWorld {
public static void main(String[] args) {
String jsonString = "[ { \"name\": \"Andrew\", \"age\": 21, \"parents\": [ { \"name\": \"Joseph\", \"age\": 18 }, { \"name\": \"Joseph\", \"age\": 18 } ] }, { \"name\": \"Maria\", \"age\": 35, \"parents\": [ { \"name\": \"Kassandra\", \"age\": 16 }, { \"name\": \"Abigail\", \"age\": 22 } ] } ]";
JSONArray json = new JSONArray(jsonString);
for(int i=0; i<json.length(); i ){
JSONObject j = json.getJSONObject(i);
System.out.println(j "\n------");
}
}
}