我正在使用Gson在我的应用程序中生成调试输出
Gson gson = new GsonBuilder().setPrettyPrinting().serializeNulls().create();
gson.toJson(myObject);
但在尝试序列化数据结构时,Gson确实抱怨循环引用错误。 这可以用杰克逊图书馆完成吗?
UPD Gson 2.3.1:2014年11月20日发布
Added support to serialize objects with self-referential fields. The self-referential field is set to null in JSON. Previous version of Gson threw a StackOverflowException on encountering any self-referential fields.
The most visible impact of this is that Gson can now serialize Throwable (Exception and Error)
答案 0 :(得分:34)
与杰克逊一起序列化:
public String serialize(Object obj, boolean pretty) {
ObjectMapper mapper = new ObjectMapper();
mapper.configure(SerializationConfig.Feature.FAIL_ON_EMPTY_BEANS, false);
if (pretty) {
return mapper.writerWithDefaultPrettyPrinter().writeValueAsString(obj);
}
return mapper.writeValueAsString(obj);
}
答案 1 :(得分:10)
杰克逊可以使用以下方法处理对象图中的循环:
@JsonIgnore
,您完全省略该属性@JsonManagedReference
和@JsonBackReference
JsonSerializer
当您仍希望提供有关该对象的某些信息但想要省略某些字段(导致该循环的字段)时,您将使用JsonSerializer
。例如:
import org.codehaus.jackson.map.JsonSerializer
import org.codehaus.jackson.JsonGenerator;
import org.codehaus.jackson.JsonProcessingException;
import org.codehaus.jackson.map.SerializerProvider;
import java.io.IOException;
public class ParentReferenceSerializer extends JsonSerializer<Parent> {
@Override
public void serialize(Parent parent, JsonGenerator jgen,
SerializerProvider provider)
throws IOException, JsonProcessingException {
jgen.writeStartObject();
writeNumberField(jgen, "id", parent.getId());
// ... other fields ...
jgen.writeEndObject();
}
}
然后在序列化的类中,您将使用@JsonSerialize
注释:
@JsonSerialize(using = ParentReferenceSerializer.class)
public Parent getParent() {
return parent;
}