简体   繁体   中英

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 ?

I am using org.codehaus.jackson.map.ObjectMapper.

Well honestly it won't work with 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.
  2. If you are tring to push so other than Object's non-existing part then it will generate erroneous things for you.

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. Conversion for B will ignore property 'c'.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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