September 08, 2018

Read a list of json objects in java sample program

Read a list of json objects in java sample program




package com.belazy.json;

import java.io.File;
import java.io.IOException;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;

public class ReadJSONList {
private ObjectMapper mapper = null;

private ObjectMapper getObjectMapper(){
if(null == mapper)
mapper = new ObjectMapper();
return mapper;
}

public static void main(String[] args) {
ReadJSONList bscPhysics = new ReadJSONList();
bscPhysics.read("D:\\PTXSANCHAYKA\\zgc_physics.json");
}

private void read(String fileName) {
JsonNode rootArray;
try {
rootArray = getObjectMapper()
.readTree(new File(fileName));
for (JsonNode root : rootArray) {
JsonNode name = root.path("name");
System.out.println("Name of the student  : " + name);
System.out.println(getObjectMapper().writeValueAsString(root));
}
} catch (JsonProcessingException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}}
}


Output



Name of the student  : "Lijesh"
{"name":"Lijesh","age":29,"cars":["Ford","BMW","Fiat"]}
Name of the student  : "Biju vas"
{"name":"Biju vas","age":32,"cars":["Ford","BMW","Fiat"]}
Name of the student  : "Smithesh"
{"name":"Smithesh","age":33,"cars":["Ford","BMW","Fiat"]}
Name of the student  : "Madhav haridas"
{"name":"Madhav haridas","age":28,"cars":["Ford","BMW","Fiat"]}
Name of the student  : "Murali Krishnan"
{"name":"Murali Krishnan","age":28,"cars":["Ford","BMW","Fiat"]}
Name of the student  : "Ranjini Raj"
{"name":"Ranjini Raj","age":28,"cars":["Ford","BMW","Fiat"]}


zgc_physics.json



[{
"name":"Lijesh",
"age":29,
"cars":[ "Ford", "BMW", "Fiat" ]
},{
"name":"Biju vas",
"age":32,
"cars":[ "Ford", "BMW", "Fiat" ]
},{
"name":"Smithesh",
"age":33,
"cars":[ "Ford", "BMW", "Fiat" ]
},{
"name":"Madhav haridas",
"age":28,
"cars":[ "Ford", "BMW", "Fiat" ]
},{
"name":"Murali Krishnan",
"age":28,
"cars":[ "Ford", "BMW", "Fiat" ]
},{
"name":"Ranjini Raj",
"age":28,
"cars":[ "Ford", "BMW", "Fiat" ]
}]




No comments:

Post a Comment

Your feedback may help others !!!

Facebook comments