Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert class to JsonElement (com.google.gson.JsonElement)

Tags:

java

json

gson

public String toJson() {
    GsonBuilder builder = new GsonBuilder();
    Gson gson = builder.create();
    return gson.toJson(this);
}

This method converts a class into a JSON string. But I want to convert a class into a JsonElement. Is this directely possible or do I have to parse the string again?

like image 961
principal-ideal-domain Avatar asked Oct 24 '25 06:10

principal-ideal-domain


1 Answers

You can use toJsonTree method of Gson class

Gson gson = new GsonBuilder().create();
JsonElement element = gson.toJsonTree(object,typeOfObject);

Reference javadoc

like image 149
mcacorner Avatar answered Oct 26 '25 19:10

mcacorner



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!