JSON – 无法使用Jackson在Object中序列化JSONObject

我有以下课程:

class A{ String abc; String def; // appropriate getters and setters with JsonProperty Annotation } 

我称Jacksons objectMapper.writeValueAsString(A)工作正常。

现在我需要添加另一个实例成员:

 class A{ String abc; String def; JSONObject newMember; // No, I cannot Stringify it, it needs to be JSONObject // appropriate getters and setters with JsonProperty Annotation } 

但是当我序列化时,我会遇到exception:

 org.codehaus.jackson.map.JsonMappingException: No serializer found for class org.json.JSONObject and no properties discovered to create BeanSerializer 

我尝试了JSONNode,但它将Output作为{outerjson: {innerjson} }而不是{outerjson:{innerjson}}。

是否可以使用Jackson实现上述输出,即JSONObject中的JSONObject?

在此处输入图像描述

好吧,如果您无法替换POJO或Map上的JSONObject,那么您可以编写自定义序列化程序 。 这是一个例子:

 public class JacksonJSONObject { public static class MyObject { public final String string; public final JSONObject object; @JsonCreator public MyObject(@JsonProperty("string") String string, @JsonProperty("object") JSONObject object) { this.string = string; this.object = object; } @Override public String toString() { return "MyObject{" + "string='" + string + '\'' + ", object=" + object + '}'; } } public static void main(String[] args) throws IOException { ObjectMapper mapper = new ObjectMapper(); SimpleModule module = new SimpleModule("org.json"); module.addSerializer(JSONObject.class, new JsonSerializer() { @Override public void serialize(JSONObject value, JsonGenerator jgen, SerializerProvider provider) throws IOException { jgen.writeRawValue(value.toString()); } }); module.addDeserializer(JSONObject.class, new JsonDeserializer() { @Override public JSONObject deserialize(JsonParser jp, DeserializationContext ctxt) throws IOException { Map bean = jp.readValueAs(new TypeReference>() {}); return new JSONObject(bean); } }); mapper.registerModule(module); JSONObject object = new JSONObject(Collections.singletonMap("key", "value")); String json = mapper.writerWithDefaultPrettyPrinter().writeValueAsString(new MyObject("string", object)); System.out.println("JSON: " + json); System.out.println("Object: " + mapper.readValue(json, MyObject.class)); } } 

输出:

 JSON: { "string" : "string", "object" : {"key":"value"} } Object: MyObject{string='string', object={"key":"value"}} 

使用JsonNode而不是JSONObject。

 JsonNode jsonNode = JsonLoader.fromString(YOUR_STRING);