Convert String to JsonObject
Using JsonParser
The first approach we’ll see for converting a JSON String
to a JsonObject
is a two-step process that uses the JsonParser
class.
we need to parse our original
String
.Once we have our
String
parsed in aJsonElement
tree, we’ll use thegetAsJsonObject()
method, which will return the desired result.
Gson provides us a parser called JsonParser
, which parses the specified JSON String
into a parse tree of JsonElements
:
public JsonElement parse(String json) throws JsonSyntaxException
Using fromJson
In our second approach, we’ll see how to create a Gson
instance and use the fromJson
method. This method deserializes the specified JSON String
into an object of the specified class:
public <T> T fromJson(String json, Class<T> classOfT) throws JsonSyntaxException
Results
ConvertStringToJsonObjectTest