在 Jackson 中映射动态 json 对象字段? [英] Mapping a dynamic json object field in Jackson?

查看:42
本文介绍了在 Jackson 中映射动态 json 对象字段?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在以下架构中有 json 对象:

I have json objects in the following schema:

{
  name: "foo",
  timestamp: 1475840608763,
  payload:
  {
     foo: "bar"
  }
}

这里的payload字段包含一个内嵌的json对象,这个对象的schema是动态的,每次都不一样.

Here, the payload field contains an embedded json object, and the schema of this object is dynamic, and different each time.

payload 对象是从不同 API 服务、不同 API 服务的不同方法获取的原始输出.不可能将其映射到所有可能的值.

The payload object is the raw output obtained from different API services, and different methods of different API services. It isn't possible to map it to all possible values.

是否有可能有一个像下面这样的java类:

Is it possible to have a java class such as the following:

public class Event
{
    public String name;
    public long timestamp;
    public JsonObject payload;
}

或者类似的东西,所以我可以接收基本模式并处理它,然后将其发送到相关类,该类会将payload转换为其适当的预期类?

Or something along those lines, so I can receive the basic schema and process it, then send it to the relevant class which will convert payload to its appropriate expected class?

推荐答案

Using JsonNode

你可以使用 JsonNode 来自 com.fasterxml.jackson.databind 包:

public class Event {

    public String name;
    public long timestamp;
    public JsonNode payload;

    // Getters and setters
}

然后使用:

String json = "{"name":"foo","timestamp":1475840608763,"
            + ""payload":{"foo":"bar"}}";

ObjectMapper mapper = new ObjectMapper();
Event event = mapper.readValue(json, Event.class);

JsonNode 映射到 POJO

考虑,例如,您要映射 JsonNode 实例到以下类:

Mapping JsonNode to a POJO

Consider, for example, you want to map the JsonNode instance to the following class:

public class Payload {

    private String foo;

    // Getters and setters
}

可以通过以下代码实现:

It can be achieved with the following piece of code:

Payload payload = mapper.treeToValue(event.getPayload(), Payload.class);

考虑一个Map

根据您的要求,您可以使用 Map 而不是 JsonNode:

public class Event {

    public String name;
    public long timestamp;
    public Map<String, Object> payload;

    // Getters and setters
}

如果您需要将 Map 转换为 POJO,请使用:

If you need to convert a Map<String, Object> to a POJO, use:

Payload payload = mapper.convertValue(event.getPayload(), Payload.class);

根据 Jackson 文档convertValue() 方法在功能上类似于先将给定值序列化为 JSON,然后将 JSON 数据绑定为值给定类型,但应该更有效,因为完全序列化不会(需要)发生.但是,将使用与数据绑定相同的转换器(串行器和解串器),这意味着相同的对象映射器配置工作.

According to the Jackson documentation, the convertValue() method is functionally similar to first serializing given value into JSON, and then binding JSON data into value of given type, but should be more efficient since full serialization does not (need to) occur. However, same converters (serializers and deserializers) will be used as for data binding, meaning same object mapper configuration works.

这篇关于在 Jackson 中映射动态 json 对象字段?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆