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

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

问题描述

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

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

我的示例类如下:

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

   //many more fields 

   //getters and setters
}

示例 Address 类是:

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.

使用杰克逊可解决此问题吗? 另外,如果在此之前有人问过这个问题,那么我就此深表歉意,因为我一直在寻找解决方案,但可能还没有看到.

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批注.型号:

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将属性序列化/反序列化为扁平化数据结构
  1. Jackson Annotation Examples
  2. Annotation Type JsonUnwrapped
  3. Jackson JSON - Using @JsonUnwrapped to serialize/deserialize properties as flattening data structure

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

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