简体   繁体   English

使用Gson将Java对象转换为JsonObject

[英]Using Gson convert Java object into JsonObject

I have a Java object, and I want to output it as a JSON string. 我有一个Java对象,我想将其输出为JSON字符串。 BUT I want to avoid printing out a property in the Java object. 但我想避免在Java对象中打印出属性。 I know that I could do this using GsonBuilder's excludeFieldsWithoutExposeAnnotation() method. 我知道我可以使用GsonBuilder的excludeFieldsWithoutExposeAnnotation()方法做到这一点。 However, I thought I'd try the alternate approach of removing the property from the JsonObject before printing it out. 但是,我想我会尝试在打印之前从JsonObject中删除属性的替代方法。 The following code works: 以下代码有效:

Gson gson = new GsonBuilder().setDateFormat("yyyy-MM-dd' 'HH:mm:ss").create();
String javaObjectString = gson.toJson(javaObject);
//javaObjectString currently include "property":"value"
JsonElement jsonElement = gson.toJsonTree(javaObjectString, javaObject.getClass());
JsonObject jsonObject = (JsonObject) jsonElement;
jsonObject.remove("property");
javaObjectString = gson.toJson(jsonObject);
//javaObjectString currently no longer includes "property":"value"

However, it feels a but hacky because I have to output the Java object to a String, and then create a JsonElement from the String, and then cast the JsonElement to a JsonObject. 但是,它感觉很糟糕,因为我必须将Java对象输出到String,然后从String创建一个JsonElement,然后将JsonElement转换为JsonObject。

Is there a more direct way to go from a Java object to a JsonObject? 有没有更直接的方法从Java对象转到JsonObject?

You don't need the intermediary String . 您不需要中间String Serialize your Java object to a JsonElement directly with Gson#toJsonTree(Object) . 使用Gson#toJsonTree(Object)直接将Java对象序列JsonElement Gson#toJsonTree(Object) Cast that value to whatever type you expect (JSON object, array, or primitive), perform your removal and invoke its toString() method to retrieve its JSON representation as a String . 将该值转换为您期望的任何类型(JSON对象,数组或基元),执行删除并调用其toString()方法以将其JSON表示形式检索为String

For example, 例如,

Gson gson = new GsonBuilder().setDateFormat("yyyy-MM-dd' 'HH:mm:ss").create();
// JSON data structure
JsonElement jsonElement = gson.toJsonTree(javaObject);
JsonObject jsonObject = (JsonObject) jsonElement;
// property removal
jsonObject.remove("property");
// serialization to String
String javaObjectString = jsonObject.toString();

You can always use the Gson#toJson overload that accepts a JsonElement to serialize it directly to a stream if you want to skip that last String object creation. 如果要跳过最后创建的String对象,可以始终使用接受JsonElementGson#toJson重载将其直接序列化为流。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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