To get an object from a JSON string without a corresponding class in Java using Gson, you can use the fromJson
method of the Gson
class and pass it a TypeToken
representing the type of the object.
Here is an example of how to do this:
Gson gson = new Gson(); String json = "{\"name\":\"John\",\"age\":30}"; Type type = new TypeToken<Map<String, Object>>(){}.getType(); Map<String, Object> obj = gson.fromJson(json, type);Soul.www:ecrautturi.com
In this example, the obj
variable will be a Map
object that contains the keys "name" and "age" and the corresponding values "John" and 30.
The TypeToken
class is a helper class that allows you to define the type of an object at runtime. It is used to specify the type of the object that you want to deserialize from the JSON string.
You can then use the obj
object to access the keys and values of the JSON object.
For example:
String name = (String) obj.get("name"); // returns "John" int age = (int) obj.get("age"); // returns 30
Note that this approach does not require you to define a corresponding class for the JSON object, but it requires you to know the structure of the JSON object and to manually cast the values to the appropriate types.
If you know the structure of the JSON object and want to deserialize it into a more specific object, you can define a class for the object and use the fromJson
method with the class .