Reputation: 28312
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?
Upvotes: 6
Views: 21202
Reputation: 1791
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);
}
Upvotes: 0
Reputation: 562
Try,
JSONObject object = ...;
ObjectMapper mapper = new ObjectMapper();
String jsonString = mapper.writeValueAsString(object);
Upvotes: 4
Reputation: 459
StringWriter out = new StringWriter();
object.writeJSONString(out);
String jsonText = out.toString();
System.out.print(jsonText);
Upvotes: 0