将 Json 字段包装到 pojo 的实例变量中 [英] Wrapping Json fields into instance variable of a pojo

查看:33
本文介绍了将 Json 字段包装到 pojo 的实例变量中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试将某些 json 字段映射到类实例变量.

i am trying to map certain json fields to a class instance variable.

我的示例 Person 类看起来像:

My sample Person class looks like:

public class Person {
   private String name;
   private Address address;

   //many more fields 

   //getters and setters
}

示例地址类是:

public class Address {
   private String street;
   private String city;
   //many more fields 

   // getters and setters
}

要反序列化为我的 Person 类的 json 对象不包含地址"字段.看起来像:

The json object to be deserialized to my Person class doesn't contain "address" field. It looks like:

{
"name":"Alexander",
"street":"abc 12",
"city":"London"
}

有没有办法将 json 反序列化到 Person pojo,其中 Address 字段也正确映射?

Is there a way to deserialize the json to the Person pojo where the Address fields are also mapped properly?

我在这里使用了很多帖子中提到的自定义地址解串器.但是,它没有被调用,因为 Json 对象不包含地址"字段.

I have used a custom Address deserializer as mentioned in so many posts here. However, it's not being called as the Json object doesn't contain "address" field.

我通过使用 JsonNode 手动映射每个字段解决了这个问题,但是在我的实际项目中,这不是一个好的解决方案.

I had resolved this problem by mapping each field manually using JsonNode, however in my real project, it's not a nice solution.

使用jackson 是否有解决此类问题的方法?另外,如果之前有人问过这个问题,那么我代表我道歉,因为我已经深入搜索了解决方案,可能还没有看到它..

Is there any work around for such problem using jackson? Plus if this question has been asked before then apologies on my behalf as as i have intensively searched for the solution and might have not seen it yet. .

推荐答案

@JsonUnwrapped 注解是针对这个问题引入的.型号:

@JsonUnwrapped annotation was introduced for this problem. Model:

class Person {
    private String name;

    @JsonUnwrapped
    private Address address;

    // getters, setters, toString
}
class Address {
    private String street;
    private String city;

    // getters, setters, toString
}

用法:

ObjectMapper mapper = new ObjectMapper();
String json = "{"name":"Alexander","street":"abc 12","city":"London"}";
System.out.println(mapper.readValue(json, Person.class));

打印:

Person{name='Alexander', address=Address{street='abc 12', city='London'}}

欲了解更多信息,请阅读:

For more info read:

  1. Jackson 注释示例
  2. 注解类型 JsonUnwrapped
  3. Jackson JSON - 使用 @JsonUnwrapped 将属性序列化/反序列化为扁平化数据结构

这篇关于将 Json 字段包装到 pojo 的实例变量中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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