The below Example will show you how to read the specific property from the file in JSON format or to read the Specific property from the JSON data.
emp.txt
{
"id": 123,
"name": "Manish",
"phone": [
123456,
987654
],
"role": "Manager",
"cities": [
"Los Angeles",
"New York"
],
"properties": {
"age": "29 years",
"salary": "1000 USD"
}
}
JSONDemo.java
package com.evon;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.Iterator;
import org.codehaus.jackson.JsonNode;
import org.codehaus.jackson.map.ObjectMapper;
public class JSONDemo {
/**
* @param args
*/
public static void main(String[] args)throws Exception {
// TODO Auto-generated method stub
byte[] jsonData = Files.readAllBytes(Paths.get("emp.txt"));
ObjectMapper objectMapper = new ObjectMapper();
//read JSON like DOM Parser
JsonNode rootNode = objectMapper.readTree(jsonData);
JsonNode nameNode = rootNode.path("name");
System.out.println("name = "+nameNode.asText());
JsonNode phoneNosNode = rootNode.path("phone");
Iterator<JsonNode> elements = phoneNosNode.getElements();
while(elements.hasNext()){
JsonNode phone = elements.next();
System.out.println("Phone's = "+phone.asLong());
}
}
}
In the above Code we have only read the specific property name and phone from the file which is in JSON format.
0 Comment(s)