我有一個場景,在運行時根據JSON值我必須將它們轉換爲選擇我們必須使用哪些JAVA類來初始化它們。 下面是兩個JSON例子使用Jackson映射JSON到Java類
JSON例1:
{
"parentVal1" : "parent Val 1",
"parentVal2" : "parent val 2",
"childVal1" : "child Val 1",
"childVal2" : {
"childPropVal1" : "child prop 1",
"grandChild" : {
"maleGrandChildVal1" : "male grand child 1",
"maleGrandChildVal2" : "male grand child 2"
}
}
}
JSON例2:現在
{
"parentVal1" : "parent Val 1",
"parentVal2" : "parent val 2",
"childVal1" : "child Val 1",
"childVal2" : {
"childPropVal1" : "child prop 1",
"grandChild" : {
"femaleGrandChildVal1" : "female grand child 1",
"femaleGrandChildVal2" : "female grand child 2"
}
}
}
,對應的Java類,我提出和類圖是
public class Parent{
private String parentVal1;
private String parentVal2;
//getters and setters
}
public class Child extends{
private String childVal1;
private ChildProperty childVal2;
//getters and setters
}
public class ChildProperty{
private String childPropVal1;
private GrandChildAbstract grandChild;
//getters and setters
}
public class GrandChildAbstract{
}
public class MaleGrandChild extends GrandChildAbstract{
private String maleGrandChildVal1;
private String maleGrandChildVal2;
//setters and getters
}
public class FemaleGrandChild extends GrandChildAbstract{
private String femaleGrandChildVal1;
private String femaleGrandChildVal2;
//setters and getters
}
的問題是在運行時,我會得到一個JSON和必須決定它是否屬於MaleGrandChild or FemaleGrandChild
取決於ChildProperty.childPropVal1
,我從JSON獲得。
任何人都可以幫助我有任何方式可以初始化ChildProperty.grandChild
財產與各自的FemaleGrandChild or MaleGrandChild
對象。
我使用Jackson從JSON轉換爲JAVA。
謝謝...我會盡力閱讀有關它.. – utkarsh31
非常感謝你的幫助..它工作... – utkarsh31