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

IAm*_*aja 2 java json jackson

我有一个JSON字符串:

{
    "fruit": {
        "weight":"29.01",
        "texture":null
    },
    "status":"ok"
}
Run Code Online (Sandbox Code Playgroud)

...我正在尝试映射回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
}
Run Code Online (Sandbox Code Playgroud)

上面的字符串(我正在尝试映射)实际上包含在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());
}
Run Code Online (Sandbox Code Playgroud)

不幸的是,当执行Jackson 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"])
Run Code Online (Sandbox Code Playgroud)

我需要映射器:

  1. 完全忽略外部花括号(“ {”和“ }”)
  2. 改变 fruitWidget
  3. status完全忽略

如果执行此操作的唯一方法是调用JSONObjecttoString()方法,那就这样吧。但是我想知道杰克逊是否提供了与Java JSON库兼容的“开箱即用”功能?

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

Sri*_*vas 5

您需要有一个PojoClass包含(has-a)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());
    }
Run Code Online (Sandbox Code Playgroud)

这是你的Widget课。

public class Widget
{    private double weight;
     private String texture;
    //getter and setters.
}
Run Code Online (Sandbox Code Playgroud)

这是你的 PojoClass

public class PojoClass
{
    private Widget fruit;
    private String status;
    //getter and setters.
}
Run Code Online (Sandbox Code Playgroud)