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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14063535/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-31 14:55:57  来源:igfitidea点击:

Mapping JSON back to POJO with JSON and Hymanson libs

javajsonHymanson

提问by IAmYourFaja

I have a JSON string:

我有一个 JSON 字符串:

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

...that I am trying to map back into a POJO:

...我正试图映射回 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
}

The string above (that I am trying to map) is actually contained inside an org.json.JSONObjectand can be obtained by calling that object's toString()method.

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

I would like to use the Hymanson JSONobject/JSON mapping framework to do this mapping, and so far this is my best attempt:

我想使用Hymanson JSONobject/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());
}

Unfortunately this code throws an exception when the Hymanson readValue(...)method gets executed:

不幸的是,当 HymansonreadValue(...)方法被执行时,这段代码会抛出一个异常:

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"])

I need the mapper to:

我需要映射器:

  1. Ignore the outer curly brackets ("{" and "}") altogether
  2. Change the fruitto a Widget
  3. Ignore the statusaltogether
  1. 完全忽略外部大括号(“ {”和“ }”)
  2. 更改fruitWidget
  3. status完全无视

If the only way to do this is to call the JSONObject's toString()method, then so be it. But I'm wondering if Hymanson comes with anything "out of the box" that already works with the Java JSON library?

如果执行此操作的唯一方法是调用JSONObjecttoString()方法,那么就这样吧。但我想知道 Hymanson 是否带有任何已经与 Java JSON 库一起使用的“开箱即用”的东西?

Either way, writing the Hymanson mapper is my main problem. Can anyone spot where I'm going wrong? Thanks in advance.

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

回答by Srinivas

You need to have a class PojoClasswhich contains (has-a) Widgetinstance called fruit.

您需要有一个PojoClass包含(has-a)Widget实例的类,称为fruit.

Try this in your mapper:

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

    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());
    }

This is your WidgetClass.

这是你的Widget班级。

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

This is your PojoClass

这是你的 PojoClass

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