【问题标题】:JSON - Unable to serialize JSONObject within Object using JacksonJSON - 无法使用 Jackson 序列化 Object 中的 JSONObject
【发布时间】:2014-06-15 14:07:59
【问题描述】:

我有以下课程:

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 
}

但是当我序列化时,我得到了异常:

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

我尝试了 JSONNode,但输出为 {outerjson:"{innerjson}"} 而不是 {outerjson:{innerjson}}。

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

【问题讨论】:

  • 你能显示给定输入的预期输出吗?
  • 为什么不用Jackson提供的ObjectNode呢?

标签: java json serialization jackson


【解决方案1】:

怎么用jackson-datatype-json-org

// import com.fasterxml.jackson.datatype.jsonorg.JsonOrgModule;

ObjectMapper mapper = new ObjectMapper();
mapper.registerModule(new JsonOrgModule());

https://github.com/FasterXML/jackson-datatype-json-org

【讨论】:

【解决方案2】:

好吧,如果你不能替换 POJO 或 Map 上的 JSONObject,那么你可以写一个custom serializer。这是一个例子:

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<JSONObject>() {
            @Override
            public void serialize(JSONObject value, JsonGenerator jgen, SerializerProvider provider) throws IOException {
            jgen.writeRawValue(value.toString());
            }
        });
        module.addDeserializer(JSONObject.class, new JsonDeserializer<JSONObject>() {
            @Override
            public JSONObject deserialize(JsonParser jp, DeserializationContext ctxt) throws IOException {
                Map<String, Object> bean = jp.readValueAs(new TypeReference<Map<String, Object>>() {});
                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"}}

【讨论】:

    【解决方案3】:

    @JsonSerialize 与属性一起使用并实现自定义序列化程序。

    @JsonSerialize(using = JsonObjectSerializer.class)
    private JSONObject jsonObject;
    
    public static class JsonObjectSerializer extends JsonSerializer<JSONObject> {
    
        @Override
        public void serialize(JSONObject jsonObject, JsonGenerator jsonGenerator, SerializerProvider serializerProvider) throws IOException {
            jsonGenerator.writeRawValue(jsonObject.toString());
        }
    }
    

    【讨论】:

      【解决方案4】:

      使用 JsonNode 代替 JSONObject。

      JsonNode jsonNode = JsonLoader.fromString(YOUR_STRING);
      

      【讨论】:

        猜你喜欢
        • 2017-09-05
        • 1970-01-01
        • 2018-12-16
        • 1970-01-01
        • 2013-01-08
        • 1970-01-01
        • 1970-01-01
        • 2015-03-13
        • 2021-05-28
        相关资源
        最近更新 更多