子对象json字符串转换为父对象

时间:2019-03-22 07:09:07

标签: java json jackson

字符串JSON继承孩子到父对象

代码基类

public class A {

    int x;

    int y;

    int z;

    public A(int x, int y, int z) {

        this.x = x;

        this.y = y;

        this.z = z;

    }

}

儿童班:

public class B  extends A {
   int i;
   int j ;

   public B(int x, int y, int z, int i, int j) {

       this.i = i;

       this.j = j;

       super(x,y,z);

   }

}

B b = new B();
// converting the obj to class obj 
String s = new ObjectMapper().writeValueAsString(b);

A a = new  ObjectMapper().convertValue(s, A.class);

B bb = (B) b;

我无法实现这一目标。 作为父类,并不具有所有字段。

属性值下降

对象A将丢失一些值,并且无法转换 父obj到子obj。

我们如何正确转换 我们应该添加@JsonProperty

2 个答案:

答案 0 :(得分:0)

首先,必须在两个类中都添加一个公共的无参数构造函数,然后您可以尝试以下方法:

        ObjectMapper mapper = new ObjectMapper();
        mapper.setVisibility(PropertyAccessor.FIELD, Visibility.ANY);
        mapper.enableDefaultTyping();
        mapper.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
        // converting the obj to class obj
        String s = mapper.writeValueAsString(b);
        A a = mapper.readValue(s, A.class);

        B bb = (B) b;

更新

您还可以向A类添加注释:

@JsonTypeInfo(use=JsonTypeInfo.Id.CLASS)

然后执行以下操作:

        ObjectMapper mapper = new ObjectMapper();
        mapper.setVisibility(PropertyAccessor.FIELD, Visibility.ANY);
       // converting the obj to class obj
        String s = mapper.writeValueAsString(b);
        A a = mapper.readValue(s, A.class);

        B bb = (B) b;

答案 1 :(得分:-1)

您可以添加 @Ason声明之前的@JsonIgnoreProperties(ignoreUnknown = true)。

import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
@JsonIgnoreProperties(ignoreUnknown = true)

class A {

 //
}