dev ray
dev ray

Reputation: 485

JSON - Unable to serialize JSONObject within Object using Jackson

I have the following class:

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

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

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.jackson.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}}.

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

enter image description here

Upvotes: 9

Views: 19506

Answers (4)

wvdz
wvdz

Reputation: 16641

Use @JsonSerialize with the attribute and implement a custom serializer.

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

Upvotes: 4

banterCZ
banterCZ

Reputation: 1869

What about to use jackson-datatype-json-org

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

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

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

Upvotes: 5

Brijesh Patel
Brijesh Patel

Reputation: 457

Use JsonNode instead of JSONObject.

JsonNode jsonNode = JsonLoader.fromString(YOUR_STRING);

Upvotes: 0

Alexey Gavrilov
Alexey Gavrilov

Reputation: 10853

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

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

Output:

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

Upvotes: 3

Related Questions