ObjectMapper class provides 'readValue' method, which can read the json content from a file and convert it to the object.
Signature
public <T> T readValue(File src, Class<T> valueType)
Example
ObjectMapper objectMapper = new ObjectMapper();
String filePath = "/Users/Shared/examples/emp.json";
HashMap<?, ?> map = objectMapper.readValue(new File(filePath), HashMap.class);
Find the below working application.
emp.json
{
"id": 1,
"firstName": "Krishna",
"lastName": "Gurram"
}
ReadJsonFromFile.java
package com.sample.app;
import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;
public class ReadJsonFromFile {
public static void main(String[] args) throws JsonParseException, JsonMappingException, IOException {
ObjectMapper objectMapper = new ObjectMapper();
String filePath = "/Users/Shared/examples/emp.json";
HashMap<?, ?> map = objectMapper.readValue(new File(filePath), HashMap.class);
System.out.println(map);
}
}
Output
{firstName=Krishna, lastName=Gurram, id=1}
No comments:
Post a Comment