1、toJsonString时WriteClassName
2、如果有泛型则需要开启类型自动转换
比如:
package com.example.springbootdemo;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.parser.ParserConfig;
import com.alibaba.fastjson.serializer.SerializerFeature;
import lombok.Data;
import org.junit.jupiter.api.Test;
public class JsonTest {
@Test
public static void main(String[] args) {
ClassA classA = new ClassA();
Address address = new Address();
address.setAddress("aaaa");
ClassB<Address> classB = new ClassB<>();
classB.setName("xxx");
classB.setAddress(address);
classA.setBase(classB);
String jsonStr = JSON.toJSONString(classA);
System.out.println(jsonStr);
ClassA copy = JSON.parseObject(jsonStr, ClassA.class);
System.out.println(JSON.toJSONString(copy));
String jsonStrWithClass = JSON.toJSONString(classA, SerializerFeature.WriteClassName);
System.out.println(jsonStrWithClass);
ParserConfig.getGlobalInstance().addAccept("com.example.springbootdemo");
ClassA rightCopy = JSON.parseObject(jsonStrWithClass, ClassA.class);
System.out.println(JSON.toJSONString(rightCopy));
}
@Data
static class ClassA {
Base base;
}
@Data
static class Base {
String name;
}
@Data
static class ClassB <T> extends Base {
T address;
}
@Data
static class Address {
String address;
}
}
|