How to convert Json to Java object using Gson

Suppose I have a json string

{"userId":"1","userName":"Yasir"} 

I now have a User class

 class User{ int userId; String userName; //setters and getters } 

Now How to convert above json string to user class object

+7
java json gson
source share
4 answers

Try the following:

 Gson gson = new Gson(); String jsonInString = "{\"userId\":\"1\",\"userName\":\"Yasir\"}"; User user= gson.fromJson(jsonInString, User.class); 
+19
source share
 User user= gson.fromJson(jsonInString, User.class); // where jsonInString is your json {"userId":"1","userName":"Yasir"} 
+3
source share
 Gson gson = new Gson(); User u=gson.fromJson(jsonstring, User.class); System.out.println("userName: "+u.getusername); 
0
source share
 Gson gson = new Gson(); User user = gson.fromJson("{\"userId\":\"1\",\"userName\":\"Yasir\"}", User.class)); 
-one
source share

All Articles