使用JSON和Jackson库将JSON映射回POJO

时间:2012-12-28 01:39:48

标签: java json jackson

我有一个JSON字符串:

{
    "fruit": {
        "weight":"29.01",
        "texture":null
    },
    "status":"ok"
}

...我正在尝试将其映射回POJO:

public class Widget {
    private double weight; // same as the weight item above
    private String texture; // same as the texture item above

    // Getters and setters for both properties
}

上面的字符串(我试图映射)实际上包含在org.json.JSONObject中,可以通过调用该对象的toString()方法获得。

我想使用Jackson JSON对象/ JSON映射框架来执行此映射,到目前为止,这是我最好的尝试:

try {
    // Contains the above string
    JSONObject jsonObj = getJSONObject();

    ObjectMapper mapper = new ObjectMapper();
    Widget w = mapper.readValue(jsonObj.toString(), Widget.class);

    System.out.println("w.weight = " + w.getWeight());
} catch(Throwable throwable) {
    System.out.println(throwable.getMessage());
}

不幸的是,当杰克逊readValue(...)方法被执行时,此代码会引发异常:

Unrecognized field "fruit" (class org.me.myapp.Widget), not marked as ignorable (2 known properties: , "weight", "texture"])
    at [Source: java.io.StringReader@26c623af; line: 1, column: 14] (through reference chain: org.me.myapp.Widget["fruit"])

我需要映射器:

  1. 完全忽略外部花括号(“{”和“}”)
  2. fruit更改为Widget
  3. 完全忽略status
  4. 如果唯一的方法是调用JSONObject的{​​{1}}方法,那么就这样吧。但我想知道杰克逊是否有任何“开箱即用”的东西已经与Java JSON库一起使用了?

    无论哪种方式,写杰克逊映射器是我的主要问题。谁能发现我哪里出错?提前谢谢。

1 个答案:

答案 0 :(得分:4)

您需要一个类PojoClass,其中包含名为Widget的(has-a)fruit实例。

在你的映射器中试试这个:

    String str = "{\"fruit\": {\"weight\":\"29.01\", \"texture\":null}, \"status\":\"ok\"}";
    JSONObject jsonObj = JSONObject.fromObject(str);
    try
    {
        // Contains the above string

        ObjectMapper mapper = new ObjectMapper();
        PojoClass p = mapper.readValue(jsonObj.toString(), new TypeReference<PojoClass>()
        {
        });

        System.out.println("w.weight = " + p.getFruit().getWeight());
    }
    catch (Throwable throwable)
    {
        System.out.println(throwable.getMessage());
    }

这是您的Widget班级。

public class Widget
{    private double weight;
     private String texture;
    //getter and setters.
}

这是您的PojoClass

public class PojoClass
{
    private Widget fruit;
    private String status;
    //getter and setters.
}
相关问题