How can we map the java object to json? Java object will have a map and some other string properties. What I want is that when we convert the java object to json that map keys should be as root key not nested key.
Sample Java Object :
class Demo {
String name;
String designation;
Map<String,Object> attribute;
}
Now if Map is having values like below :
Map<String,Object> attribute = new HashMap<>();
attribute.put("score",190);
attribute.put("status","allowed");
Output should be like below:
{
"name":"jack",
"designation":"Tester",
"score":190,
"status":"allowed"
}
If I get you right - use Jackson. Example:
Java Objects to JSON
ObjectMapper mapper = new ObjectMapper();
// Java object to JSON file
mapper.writeValue(new File("c:\\test\\staff.json"), new Staff());
// Java object to JSON string
String jsonString = mapper.writeValueAsString(object);
JSON to Java Objects
ObjectMapper mapper = new ObjectMapper();
//JSON file to Java object
Staff obj = mapper.readValue(new File("c:\\test\\staff.json"), Staff.class);
//JSON URL to Java object
Staff obj = mapper.readValue(new URL("http://some-domains/api/name.json"), Staff.class);
//JSON string to Java Object
Staff obj = mapper.readValue("{'name' : 'mkyong'}", Staff.class);
Repo: https://mvnrepository.com/artifact/com.fasterxml.jackson.core/jackson-databind
Jackson JSON Tutorial: https://www.baeldung.com/jackson
Another example: https://mkyong.com/java/jackson-2-convert-java-object-to-from-json/
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.