我正在使用杰克逊并且能够获得JSONObject
。我需要能够将此JSONObject
转换为json
形式。含义,由此JSONObject
的子字符串表示的对象。
类似的东西:
JsonObject object = ...;
object.toJsonString();
一个简单的谷歌搜索令人惊讶地没有发现很多回复,我无法看到如何自己做。
有什么想法吗?
答案 0 :(得分:4)
尝试,
JSONObject object = ...;
ObjectMapper mapper = new ObjectMapper();
String jsonString = mapper.writeValueAsString(object);
答案 1 :(得分:0)
StringWriter out = new StringWriter();
object.writeJSONString(out);
String jsonText = out.toString();
System.out.print(jsonText);
答案 2 :(得分:0)
如果需要桥接两个API,则可以创建自定义StdSerializer。 有关自定义序列化器的更多信息: 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);
}