How to parse json to pojo for a dynamic property variable in java.
Rest api returns data:
"db": {
"queryA": {
"name": "A",
"age": "12",
"startDT": "202102030800"
}
}
OR sometimes
"db":{
"queryA":
{
"name": "A",
"age": "12",
"startDT": "202102030800"
},
"queryB":
{
"name": "B",
"age": "20",
"startDT": "202102030800"
}
}
Sometimes query is an Object and sometime it is two Object.
How to map this dynamic query into java Pojo class.
class Student{
private Query query;
}
You need to consider the 'db' attribute as a Map. The queries, eg 'queryA', 'queryB', ... etc. would be keys and their corresponding objects their values. Refer the below example:
The fileA JSON (the 1st example JSON as provided):
{
"db": {
"queryA": {
"name": "A",
"age": "12",
"startDT": "202102030800"
}
}
}
The fileB JSON (the 2nd example JSON as provided)
{
"db":{
"queryA":
{
"name": "A",
"age": "12",
"startDT": "202102030800"
},
"queryB":
{
"name": "B",
"age": "20",
"startDT": "202102030800"
}
}
}
The data (deserialized) class"
package org.test.json;
import java.util.HashMap;
public class DataClass {
protected HashMap<String, Object> db;
public HashMap<String, Object> getDb() {return db;}
public void setDb(HashMap<String, Object> db) {this.db = db;}
}//calss closing
The Jackson deserialization code:
package org.test.json;
import java.io.FileInputStream;
import com.fasterxml.jackson.databind.ObjectMapper;
public class VariableLengthAttrToMap {
public static void main(String[] args) throws Exception{
String jsonFilePath="D:\\workspaces\\mtplatform\\TechTest\\testfiles\\fileB.json";
FileInputStream fis=new FileInputStream(jsonFilePath);
ObjectMapper mapper=new ObjectMapper();
System.out.println(mapper.readValue(fis, DataClass.class).getDb());
fis.close();
}//main closing
}//class closing
The result for fileA as input is
{queryA={name=A, age=12, startDT=202102030800}}
The result for fileB as input is
{queryA={name=A, age=12, startDT=202102030800}, queryB={name=B, age=20, startDT=202102030800}}
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.