java 在 Jackson 中读取嵌入的对象

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10036530/
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-30 23:21:12  来源:igfitidea点击:

Read embedded object in Hymanson

javajsonmappingHymanson

提问by Crozin

I'm trying to read a legacy JSON code using Hymanson 2.0-RC3, however I'm stuck with an "embedded" object.

我正在尝试使用 Hymanson 2.0-RC3 读取旧的 JSON 代码,但是我遇到了“嵌入式”对象。

Given a following JSON:

给定以下 JSON:

{
    "title": "Hello world!",
    "date": "2012-02-02 12:23:34".
    "author": "username",
    "author_avatar": "http://.../",
    "author_group": 123,
    "author_prop": "value"
}

How can I map it into the following structure:

如何将其映射到以下结构中:

class Author {
    @JsonPropery("author")
    private String name;

    @JsonPropery("author_avatar")
    private URL avatar;

    @JsonProperty("author_group")
    private Integer group;

    ...
}

class Item {
    private String title;

    @JsonProperty("date")
    private Date createdAt;

    // How to map this?
    private Author author;
}

I was trying to do that with @JsonDeserializebut it seems that I'd have to map the entire Itemobject that way.

我试图这样做,@JsonDeserialize但似乎我必须以Item这种方式映射整个对象。

回答by Bruno Hansen

To deal with an "embedded" object you should use @JsonUnwrapped— it's an equivalent of the Hibernate's @Embeddable/@Embedded.

要处理您应该使用的“嵌入式”对象@JsonUnwrapped——它相当于 Hibernate 的@Embeddable/ @Embedded

class Item {
    private String title;

    @JsonProperty("date")
    private Date createdAt;

    // How to map this?
    @JsonUnwrapped
    private Author author;
}

回答by c_maker

I would deserialize the original JSON to a single, flat object first (kind of like an adapter), then create your own domain objects.

我会首先将原始 JSON 反序列化为单个平面对象(有点像适配器),然后创建您自己的域对象。

class ItemLegacy {
    private String title;

    @JsonProperty("date")
    private Date createdAt;

    @JsonPropery("author")
    private String name;

    @JsonPropery("author_avatar")
    private URL avatar;

    @JsonProperty("author_group")
    private Integer group;

    @JsonProperty("author_prop")
    private Integer group;
}

Then use this object to fill out your Item and Author objects and create the correct relationships.

然后使用此对象填写您的 Item 和 Author 对象并创建正确的关系。

 //... the deserialized original JSON
 ItemLegacy legacy ...

 // create an author
 Author author = new Author();
 author.setName(legacy.getName());
 author.setGroup(legacy.getGroup());
 ...

 // create an item
 Item item = new Item();
 item.setTitle(legacy.getTitle());
 ...

 // finally set the author... and you should have the desired structure
 item.setAuthor(author);

YourItemclass could only be automatically deserialized fromthe following form:

您的Item只能从以下形式自动反序列化:

{
    "title": "Hello world!",
    "date": "2012-02-02 12:23:34".
    "author": { 
                "name": "username", 
                "author_avatar": "http://...", 
                "author_group": "123", 
                "author_prop": "value" 
              }
}

You might be able to do something with custom deserialization, but it would not be the simpler solution for sure.

您也许可以使用自定义反序列化来做一些事情,但这肯定不是更简单的解决方案。

回答by bdoughan

Note:I'm the EclipseLink JAXB (MOXy)lead and a member of the JAXB 2 (JSR-222)expert group.

注意:我是EclipseLink JAXB (MOXy) 的负责人和JAXB 2 (JSR-222)专家组的成员。

I'm not sure if Hymanson supports this use case, but below is an example of how you can leverage MOXy's @XmlPathextension to meet your requirements. Note you will need to use an EclipseLink 2.4.0 nightly label from April 7, 2012 or newer.

我不确定 Hymanson 是否支持这个用例,但下面是一个示例,说明如何利用 MOXy 的@XmlPath扩展来满足您的要求。请注意,您需要使用 2012 年 4 月 7 日或更新版本的 EclipseLink 2.4.0 nightly 标签。

Item

物品

The authorproperty on Itemis mapped with @XmlPath('.'). This means that the content of Authoris pulled up to the same level as the content for Item. I also needed to use an XmlAdapterfor the Dateproperty as the format you are using doesn't match MOXy's default representation.

author物业上Item映射有@XmlPath('.')。这意味着 的内容Author被上拉到与 的内容相同的级别Item。我还需要XmlAdapterDate属性使用 ,因为您使用的格式与 MOXy 的默认表示不匹配。

package forum10036530;

import java.util.Date;
import javax.xml.bind.annotation.*;
import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter;
import org.eclipse.persistence.oxm.annotations.XmlPath;

@XmlAccessorType(XmlAccessType.FIELD)
class Item {
    private String title;

    @XmlElement(name="date")
    @XmlJavaTypeAdapter(DateAdapter.class)
    private Date createdAt;

    @XmlPath(".")
    private Author author;
}

Author

作者

package forum10036530;

import java.net.URL;
import javax.xml.bind.annotation.*;

@XmlAccessorType(XmlAccessType.FIELD)
class Author {
    @XmlElement(name="author")
    private String name;

    @XmlElement(name="author_avatar")
    private URL avatar;

    @XmlElement(name="author_group")
    private Integer group;

    @XmlElement(name="author_prop")
    private String prop;
}

DateAdapter

日期适配器

package forum10036530;

import java.text.SimpleDateFormat;
import java.util.Date;
import javax.xml.bind.annotation.adapters.XmlAdapter;

public class DateAdapter extends XmlAdapter<String, Date> {

    private SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");

    @Override
    public Date unmarshal(String string) throws Exception {
        return dateFormat.parse(string);
    }

    @Override
    public String marshal(Date date) throws Exception {
        return dateFormat.format(date);
    }

}

jaxb.properties

jaxb.properties

A file called jaxb.propertieswith the following entry must be placed in the same package as the domain classes to specify MOXy as the JAXB (JSR-222) provider.

jaxb.properties必须将使用以下条目调用的文件与域类放在同一个包中,以将 MOXy 指定为 JAXB (JSR-222) 提供程序。

javax.xml.bind.context.factory = org.eclipse.persistence.jaxb.JAXBContextFactory

input.json/Output

输入.json/输出

{
   "title" : "Hello world!",
   "date" : "2012-02-02 12:23:34",
   "author" : "username",
   "author_avatar" : "http://www.example.com/foo.png",
   "author_group" : 123,
   "author_prop" : "value"
}

For More Information

想要查询更多的信息