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:
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.
Is there a more direct way to go from a Java object to a JsonObject?
Converting Java object to JSON In it, create an object of the POJO class, set required values to it using the setter methods. Instantiate the ObjectMapper class. Invoke the writeValueAsString() method by passing the above created POJO object. Retrieve and print the obtained JSON.
We can also add a JSONArray to JSONObject. We need to add a few items to an ArrayList first and pass this list to the put() method of JSONArray class and finally add this array to JSONObject using the put() method.
Gson Goals: Provide simple toJson() and fromJson() methods to convert Java objects to JSON and vice-versa. Allow pre-existing unmodifiable objects to be converted to and from JSON. Extensive support of Java Generics.
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
.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With