0

我收到了一个 Json 文件,格式如下:

{
    "descriptions": {
        "desc1": "someString",
        "desc2": {"name":"someName", "val": 7.0}
    }
}

我有 POJO:

public class CustomClass {
    Map<String, Object> descriptions;
    public static class NameVal{
        String name;
        double val;
        public NameVal(String name, double val){...}
    }
}

我可以使用以下代码重新创建 json 文件:

CustomClass a = new CustomClass();
a.descriptions = new HashMap<String, Object>();
a.descriptions.put("desc1", "someString");
a.descriptions.put("desc2", new CustomClass.NameVal("someName", 7.0));
new ObjectMapper().writeValue(new File("testfile"), a);

但是,当我在使用中读取对象时:

CustomClass fromFile = new ObjectMapper().readValue(new File("testfile"), CustomClass.class);

那么 fromFile.descriptions.get("desc2") 是 LinkedHashMap 类型而不是 CustomClass.NameVal 类型。

如何让 Jackson 正确解析 CustomClass.NameVal 描述符的类型(除了制作一些包装解析并在 Jackson 读取文件后显式转换 LinkedHashMap 的类)?

4

2 回答 2

0

你可以尝试这样的事情:

public class DescriptionWrapper {
    private Description descriptions;

    public Description getDescriptions() {
        return descriptions;
    }

    public void setDescriptions(Description descriptions) {
        this.descriptions = descriptions;
    }
}

public class Description {
    private String desc1;
    private NameValue desc2;

    public String getDesc1() {
        return desc1;
    }

    public void setDesc1(String desc1) {
        this.desc1 = desc1;
    }

    public NameValue getDesc2() {
        return desc2;
    }

    public void setDesc2(NameValue desc2) {
        this.desc2 = desc2;
    }
}

public class NameValue {
    private String name;
    private double val;

    public String getName() {
         return name;
    }

    public void setName(String name) {
         this.name = name;
    }

    public double getVal() {
         return val;
    }

    public void setVal(double val) {
         this.val = val;
    }
}    
于 2013-06-12T10:45:55.740 回答
0

尝试这个。创建具有名称和值属性的类描述:

public class Description {
    private String name;
    private double val;
}

现在在您的 CustomClass 中执行以下操作:

public class CustomClass {
     List<Description> descriptions;
}

就是这样。记住要创建 getter 和 setter,因为 Jackson 需要它。

于 2013-06-10T23:19:10.527 回答