Java JSON - 无法使用 Jackson 在对象中序列化 JSONObject

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/23368014/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-13 22:17:13  来源:igfitidea点击:

JSON - Unable to serialize JSONObject within Object using Hymanson

javajsonserializationHymanson

提问by dev ray

I have the following class:

我有以下课程:

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

and I call Hymansons objectMapper.writeValueAsString(A)which works fine.

我称之为Hymansons objectMapper.writeValueAsString(A)工作正常。

Now I need to add another instance member:

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

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 
}

but when I serialize, I am getting exception:

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

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

I tried JSONNode but it gave Output as {outerjson:"{innerjson}"} not {outerjson:{innerjson}}.

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

Is it possible to use Hymanson to achieve the above output, i.e. JSONObject within JSONObject?

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

enter image description here

enter image description here

回答by Alexey Gavrilov

Well, if you cannot replace the JSONObject on a POJO or a Map, then you can write a custom serializer. Here is an example:

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

public class HymansonJSONObject {

    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));
    }
}

Output:

输出:

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

回答by Brijesh Patel

Use JsonNode instead of JSONObject.

使用 JsonNode 而不是 JSONObject。

JsonNode jsonNode = JsonLoader.fromString(YOUR_STRING);

回答by banterCZ

What about to use Hymanson-datatype-json-org

要用什么 Hymanson-datatype-json-org

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

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

See https://github.com/FasterXML/Hymanson-datatype-json-org

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

回答by wvdz

Use @JsonSerializewith the attribute and implement a custom serializer.

@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());
    }
}