java gson get object without class

java gson get object without class

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);
Sou‮l.www:ecr‬autturi.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 .

Created Time:2017-11-03 22:21:12  Author:lautturi