Firstly I suggest you to take a look at Gson docs and JSON specs because it looks like you're rather lost...
With Gson, the normal and the easiest way to parse your JSON is creating a structure of Java classes that matches the structure of your JSON.
In this case, your JSON is an object (it's surrounded by { }
) and contains a number of properties (i.e., type
, password
, role
, etc.).
So, what you need is to create a Java class with those properties (matching the names):
class User
String type
String password
String role
// ...
Then you just need to call Gson, give it some JSON string and tell it in which class you want that JSON to be parsed into:
User someUser = gson.fromJson( yourJson, User.class );
EDIT: If your JSON may change, you cannot use a single class to parse it, so you have a couple of options. Probably the easiest one is to try to parse your JSON into a Map
structure.
A Map
is an object (like your JSON is) that contains pairs Key=>Value
(e.g., 'type'=>1
). So you can try to parse it likt this:
Type mapType = new TypeToken< Map<String, String> >() {}.getType();
HashMap<String, String> map = gson.fromJson( yourJson, mapType );
Note: the problem with this approach is that, as Java is a strongly-typed language, your JSON has to have pairs of the same type (e.g., ). In this case, your fields 'type'
and 'age'
are not strings, but integers, but I'm pretty sure it can automatically convert them into strings...
If it can't, or if it's really important to parse 'type'
and 'age'
into integers, your only option is to write a Custom Deserializer...