使用Gson序列化具有相同类型的类成员的对象时,我面临着这个问题:
https://github.com/google/gson/issues/1447
对象:
public class StructId implements Serializable {
private static final long serialVersionUID = 1L;
public String Name;
public StructType Type;
public StructId ParentId;
public StructId ChildId;
并且由于StructId包含具有相同类型的ParentId / ChildId,因此在尝试对其进行序列化时我遇到了无限循环,所以我要做的是:
private Gson gson = new GsonBuilder()
.setExclusionStrategies(new ExclusionStrategy() {
public boolean shouldSkipClass(Class<?> clazz) {
return false; //(clazz == StructId.class);
}
/**
* Custom field exclusion goes here
*/
public boolean shouldSkipField(FieldAttributes f) {
//Ignore inner StructIds to solve circular serialization
return ( f.getName().equals("ParentId") || f.getName().equals("ChildId") );
}
})
/**
* Use serializeNulls method if you want To serialize null values
* By default, Gson does not serialize null values
*/
.serializeNulls()
.create();
但这还不够好,因为我需要Parent / Child内部的数据,而在序列化时却无法解决它们。 怎么解决呢?
与标记为“解决方案”的答案有关:
我有这样一个结构: -结构1 -桌子 --- Variable1
如您所见,Table的ParentId为“ Struct1”,但“ Struct1”的ChildId为空,应为“ Table”
B.R。
答案 0 :(得分:1)
我认为使用ExclusionStrategy
是解决此问题的正确方法。
我宁愿建议使用JsonSerializer
和JsonDeserializer
为您的StructId
类定制。
(使用TypeAdapter
的方法可能会更好,
但是我没有足够的Gson经验来完成这项工作。)
因此,您可以通过以下方式创建Gson
实例:
Gson gson = new GsonBuilder()
.registerTypeAdapter(StructId.class, new StructIdSerializer())
.registerTypeAdapter(StructId.class, new StructIdDeserializer())
.setPrettyPrinting()
.create();
下面的StructIdSerializer
类负责将StructId
转换为JSON。
它将其属性Name
,Type
和ChildId
转换为JSON。
请注意,它不会将属性ParentId
转换为JSON,
因为这样做会产生无限递归。
public class StructIdSerializer implements JsonSerializer<StructId> {
@Override
public JsonElement serialize(StructId src, Type typeOfSrc, JsonSerializationContext context) {
JsonObject jsonObject = new JsonObject();
jsonObject.addProperty("Name", src.Name);
jsonObject.add("Type", context.serialize(src.Type));
jsonObject.add("ChildId", context.serialize(src.ChildId)); // recursion!
return jsonObject;
}
}
下面的StructIdDeserializer
类负责将JSON转换为StructId
。
它将转换JSON属性Name
,Type
和ChildId
到StructId
中相应的Java字段。
请注意,ParentId
Java字段是根据JSON嵌套结构重建的,
因为它没有直接包含为JSON属性。
public class StructIdDeserializer implements JsonDeserializer<StructId> {
@Override
public StructId deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context)
throws JsonParseException {
StructId id = new StructId();
id.Name = json.getAsJsonObject().get("Name").getAsString();
id.Type = context.deserialize(json.getAsJsonObject().get("Type"), StructType.class);
JsonElement childJson = json.getAsJsonObject().get("ChildId");
if (childJson != null) {
id.ChildId = context.deserialize(childJson, StructId.class); // recursion!
id.ChildId.ParentId = id;
}
return id;
}
}
我通过此JSON输入示例测试了上面的代码
{
"Name": "John",
"Type": "A",
"ChildId": {
"Name": "Jane",
"Type": "B",
"ChildId": {
"Name": "Joe",
"Type": "A"
}
}
}
通过StructId root = gson.fromJson(new FileReader("example.json"), StructId.class);
,System.out.println(gson.toJson(root));
答案 1 :(得分:0)
仅显示一种使用TypeAdapter
和ExclusionStrategy
进行序列化(因此我不处理反序列化)的方法。这可能不是最漂亮的实现,但还是很通用的。
此解决方案利用以下事实:您的结构是某种双向链接列表,并且给定该列表中的任何节点,我们只需要分开父级和子级的序列化,以便将它们仅在一个方向上序列化即可避免循环引用。
首先,我们需要可配置的ExclusionStrategy
,例如:
public class FieldExclusionStrategy implements ExclusionStrategy {
private final List<String> skipFields;
public FieldExclusionStrategy(String... fieldNames) {
skipFields = Arrays.asList(fieldNames);
}
@Override
public boolean shouldSkipField(FieldAttributes f) {
return skipFields.contains(f.getName());
}
@Override
public boolean shouldSkipClass(Class<?> clazz) {
return false;
}
}
然后TypeAdapter
就像:
public class LinkedListAdapter extends TypeAdapter<StructId> {
private static final String PARENT_ID = "ParentId";
private static final String CHILD_ID = "ChildId";
private Gson gson;
@Override
public void write(JsonWriter out, StructId value) throws IOException {
// First serialize everything but StructIds
// You could also use type based exclusion strategy
// but for brevity I use just this one
gson = new GsonBuilder()
.addSerializationExclusionStrategy(
new FieldExclusionStrategy(CHILD_ID, PARENT_ID))
.create();
JsonObject structObject = gson.toJsonTree(value).getAsJsonObject();
JsonObject structParentObject;
JsonObject structChildObject;
// If exists go through the ParentId side in one direction.
if(null!=value.ParentId) {
gson = new GsonBuilder()
.addSerializationExclusionStrategy(new FieldExclusionStrategy(CHILD_ID))
.create();
structObject.add(PARENT_ID, gson.toJsonTree(value.ParentId));
if(null!=value.ParentId.ChildId) {
gson = new GsonBuilder()
.addSerializationExclusionStrategy(new FieldExclusionStrategy(PARENT_ID))
.create();
structParentObject = structObject.get(PARENT_ID).getAsJsonObject();
structParentObject.add(CHILD_ID, gson.toJsonTree(value.ParentId.ChildId).getAsJsonObject());
}
}
// And also if exists go through the ChildId side in one direction.
if(null!=value.ChildId) {
gson = new GsonBuilder()
.addSerializationExclusionStrategy(new FieldExclusionStrategy(PARENT_ID))
.create();
structObject.add(CHILD_ID, gson.toJsonTree(value.ChildId));
if(null!=value.ChildId.ParentId) {
gson = new GsonBuilder()
.addSerializationExclusionStrategy(new FieldExclusionStrategy(CHILD_ID))
.create();
structChildObject = structObject.get(CHILD_ID).getAsJsonObject();
structChildObject.add(PARENT_ID, gson.toJsonTree(value.ChildId.ParentId).getAsJsonObject());
}
}
// Finally write the combined result out. No need to initialize gson anymore
// since just writing JsonElement
gson.toJson(structObject, out);
}
@Override
public StructId read(JsonReader in) throws IOException {
return null;
}}
测试:
@Slf4j
public class TestIt extends BaseGsonTest {
@Test
public void test1() {
StructId grandParent = new StructId();
StructId parent = new StructId();
grandParent.ChildId = parent;
parent.ParentId = grandParent;
StructId child = new StructId();
parent.ChildId = child;
child.ParentId = parent;
Gson gson = new GsonBuilder()
.setPrettyPrinting()
.registerTypeAdapter(StructId.class, new LinkedListAdapter())
.create();
log.info("\n{}", gson.toJson(parent));
}}
会给你类似的东西
{
"Name": "name1237598030",
"Type": {
"name": "name688766789"
},
"ParentId": {
"Name": "name1169146729",
"Type": {
"name": "name2040352617"
}
},
"ChildId": {
"Name": "name302155142",
"Type": {
"name": "name24606376"
}
}
}
我的考试材料中的名称默认情况下仅使用"name"+hashCode()
答案 2 :(得分:0)
根据这篇文章,很抱歉误导你们:
Is there a solution about Gson "circular reference"?
“ Gson中没有自动的循环引用解决方案。我知道的唯一可以自动处理循环引用的JSON生成库是XStream(带有Jettison后端)。”
但这是您不使用杰克逊的情况!如果您已经使用Jackson来构建REST API控制器,那么为什么不使用它进行序列化呢?不需要像Gson或XStream这样的外部组件。
杰克逊的解决方案:
序列化:
ObjectWriter ow = new ObjectMapper().writer().withDefaultPrettyPrinter();
try {
jsonDesttinationIdString = ow.writeValueAsString(destinationId);
} catch (JsonProcessingException ex) {
throw new SpecificationException(ex.getMessage());
}
反序列化:
ObjectMapper mapper = new ObjectMapper();
try {
destinationStructId = destinationId.isEmpty() ? null : mapper.readValue(URLDecoder.decode(destinationId, ENCODING), StructId.class);
} catch (IOException e) {
throw new SpecificationException(e.getMessage());
}
最重要的是,您必须使用@JsonIdentityInfo批注:
//@JsonIdentityInfo(
// generator = ObjectIdGenerators.PropertyGenerator.class,
// property = "Name")
@JsonIdentityInfo(
generator = ObjectIdGenerators.UUIDGenerator.class,
property = "id")
public class StructId implements Serializable {
private static final long serialVersionUID = 1L;
@JsonProperty("id") // I added this field to have a unique identfier
private UUID id = UUID.randomUUID();