使用 Gson 将 Java 对象转换为 JsonObject
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/47193364/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Using Gson convert Java object into JsonObject
提问by user304582
I have a Java object, and I want to output it as a JSON string. BUT I want to avoid printing out a property in the Java object. I know that I could do this using GsonBuilder's excludeFieldsWithoutExposeAnnotation() method. However, I thought I'd try the alternate approach of removing the property from the JsonObject before printing it out. The following code works:
我有一个 Java 对象,我想将它输出为 JSON 字符串。但我想避免打印出 Java 对象中的属性。我知道我可以使用 GsonBuilder 的 excludeFieldsWithoutExposeAnnotation() 方法来做到这一点。但是,我想我会尝试在打印之前从 JsonObject 中删除属性的替代方法。以下代码有效:
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.
但是,感觉有点hacky,因为我必须将Java对象输出到String,然后从String创建一个JsonElement,然后将JsonElement转换为JsonObject。
Is there a more direct way to go from a Java object to a JsonObject?
有没有更直接的方法可以从 Java 对象转到 JsonObject?
回答by Sotirios Delimanolis
You don't need the intermediary String
. Serialize your Java object to a JsonElement
directly with 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
.
你不需要中介String
。将您的 Java 对象JsonElement
直接序列化为Gson#toJsonTree(Object)
. 将该值转换为您期望的任何类型(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.
如果您想跳过最后一个对象的创建,您始终可以使用Gson#toJson
接受 a的重载JsonElement
将其直接序列化为流String
。