fastjson 嵌套类型时,怎么才能反序列化成子类

np8igboo  于 2021-11-27  发布在  Java
关注(0)|答案(2)|浏览(882)

嵌套子类Child,反序列化后,不是Child,而是Parent,需要怎么处理呢
public class JsonTest {
 @test public void test() {
  Shell shell = new Shell(new Child(13).setName("zs"));
  String json = JSON.toJSONString(shell);
  log.info("json: {}", json); // 输出 {"parent":{"age":13,"name":"zs"}}
  Shell after = JSON.parseObject(json, Shell.class);
  log.info("after json: {}", JSON.toJSONString(after, SerializerFeature.WriteClassName)); // 这里输出,缺少子类age字段,因为示例化成了父类Parent
 }
}
@DaTa@AllArgsConstructor@NoArgsConstructor
classShell{ // 壳
 private Parent parent;
}
classParent{ // 父类
 @getter private String name;
 public Parent setName(String name) {
  this.name = name;
  return this;
 }
}
@DaTa@EqualsAndHashCode(callSuper = false)@AllArgsConstructor@NoArgsConstructor
classChildextendsParent{ // 子类
 private Integer age;
}

nvbavucw

nvbavucw1#

这样写不起作用
Shell after = JSON.parseObject(json, Shell.class, (FieldTypeResolver) (object, fieldName) -> {
 if (fieldName.equals("parent")) {
  return Child.class;
 }
 return null;
});

uurity8g

uurity8g2#

package com.alibaba.json.bvt.issue_3400;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializerFeature;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.Getter;
import lombok.NoArgsConstructor;
import org.junit.Test;

public class Issue3486 {
    @Test
    public void test() {
        Shell shell = new Shell(new Child(13).setName("zs"));
        String json = JSON.toJSONString(shell, SerializerFeature.WriteClassName);
        System.out.printf("json: %s\n", json); // 输出 {"parent":{"age":13,"name":"zs"}}
        Shell after = JSON.parseObject(json, Shell.class);
        System.out.printf("after json: %s\n", JSON.toJSONString(after, SerializerFeature.WriteClassName)); // 这里输出,缺少子类age字段,因为示例化成了父类Parent
    }
}

@Data
@AllArgsConstructor
@NoArgsConstructor
class Shell { // 壳
    private Parent parent;
}

@Getter
class Parent { // 父类
    private String name;

    public Parent setName(String name) {
        this.name = name;
        return this;
    }
}

@Data
@EqualsAndHashCode(callSuper = false)
@AllArgsConstructor
@NoArgsConstructor
class Child extends Parent { // 子类
    private Integer age;
}

输出

json: {"@type":"com.alibaba.json.bvt.issue_3400.Shell","parent":{"@type":"com.alibaba.json.bvt.issue_3400.Child","age":13,"name":"zs"}}
after json: {"@type":"com.alibaba.json.bvt.issue_3400.Shell","parent":{"@type":"com.alibaba.json.bvt.issue_3400.Child","age":13,"name":"zs"}}

相关问题