2

我有一个 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 object/JSON mapping framework 来做这个映射,到目前为止这是我最好的尝试:

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(...)不幸的是,当执行 Jackson 方法时,这段代码会引发异常:

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. 将 更改fruitWidget
  3. status完全忽略

如果这样做的唯一方法是调用JSONObject'toString()方法,那就这样吧。但是我想知道 Jackson 是否带有任何已经与 Java JSON 库一起使用的“开箱即用”的东西?

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

4

1 回答 1

5

您需要有一个PojoClass包含(具有)Widget实例的类,称为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.
}
于 2012-12-28T05:22:22.513 回答