简体   繁体   English

使用对象映射器从json字符串读取额外的字段

[英]Reading extra field from json string using object mapper

Class A {
    String a;
    String b;
    String c;
}

Class B {
    String a;
    String b;
}

I wish to read one json string jString of class A using ObjectMapper.readValue (jString, B.class), Could i pass some parameter, which would help me also read c but in some other structure ? 我想使用ObjectMapper.readValue(jString,B.class)读取类A的一个json字符串jString,我可以传递一些参数,这也可以帮助我读取c,但使用其他结构吗?

I am using org.codehaus.jackson.map.ObjectMapper. 我正在使用org.codehaus.jackson.map.ObjectMapper。

Well honestly it won't work with ObjectMapper. 老实说,它不能与ObjectMapper一起使用。

If you do this, 如果这样做

ObjectMapper.readValue (jString, B.class),
  1. so, library always parse vales from json String and assign it to B, with the help of B's getter and setter method. 因此,在B的getter和setter方法的帮助下,库总是从json String中解析值并将其分配给B。
  2. If you are tring to push so other than Object's non-existing part then it will generate erroneous things for you. 如果您打算不使用Object不存在的部分而进行推送,那么它将为您生成错误的信息。

It's better to first prepare such type of Object then do it. 最好先准备这种类型的对象然后再做。

If you intend to create instances of both class A and class B, you can read json twice to create instances. 如果打算同时创建A类和B类的实例,则可以两次读取json以创建实例。 Conversion for B will ignore property 'c'. B的转换将忽略属性“ c”。

A a = mapper.readValue(jString, A.class);
B b = mapper.readValue(jString, B.class);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM