简体   繁体   中英

Convert JsonObject to Json String with Jackson

I am using Jackson and am able to get a JSONObject . I need to be able to convert this JSONObject to its json form. Meaning, the object that is represented by this JSONObject 's son string.

Something like:

JsonObject object = ...;
object.toJsonString();

A simple Google search surprisingly didn't turn up many response and I am unable to see how to do it on my own.

Any ideas?

Try,

JSONObject object = ...;
ObjectMapper mapper = new ObjectMapper();
String jsonString = mapper.writeValueAsString(object);
  StringWriter out = new StringWriter();
  object.writeJSONString(out);

  String jsonText = out.toString();
  System.out.print(jsonText);

If you need to bridge the 2 APIs you can create a custom StdSerializer. More on custom serializers: https://www.baeldung.com/jackson-custom-serialization

private static class JSONObjectSerializer extends StdSerializer<JSONObject> {

    JSONObjectSerializer(){
        this(null);
    }

    JSONObjectSerializer(Class<JSONObject> t) {
        super(t);
    }

    @Override public void serialize(JSONObject value, JsonGenerator gen, SerializerProvider provider) throws IOException {
        gen.writeStartObject();
        value.keys().forEachRemaining(key-> {
            try {
                gen.writeStringField(key,value.getString(key));
            } catch (IOException ex){
                throw new RuntimeException("Encountered an error serializing the JSONObject.",ex);
            }
        });
        gen.writeEndObject();
    }

    private static SimpleModule toModule(){
        return new SimpleModule().addSerializer(JSONObject.class, new JSONObjectSerializer());
    }
}

//.......

ObjectWriter writer = new ObjectMapper()
    .registerModule(JSONObjectSerializer.toModule())
    .writerWithDefaultPrettyPrinter();

//.......

try {
    s = w.writeValueAsString(v);// v being your JSONObject or parent
} catch (JsonProcessingException ex) {
    throw new RuntimeException("Unable to write object to json.", ex);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM