34

Suppose I have json string

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

now I have a class User

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

Now How can I convert above json string to user class object

2
  • 1
    User user=new Gson().fromJson(yourJsonString,User.class); Commented Sep 28, 2017 at 10:41
  • 1
    As an FYI to anyone starting out with just JSON - from an API they're consuming say: There are a lot of services - utilities and online - which can take the JSON and generate the corresponding class or nested classes automatically. for example pojo.sodhanalibrary.com . So you can just drop those POJOS into your project and still use the top answer. saves time and typos. Commented Nov 9, 2017 at 14:13

4 Answers 4

71

Try this:

Gson gson = new Gson();
String jsonInString = "{\"userId\":\"1\",\"userName\":\"Yasir\"}";
User user= gson.fromJson(jsonInString, User.class);
Sign up to request clarification or add additional context in comments.

Comments

7
User user= gson.fromJson(jsonInString, User.class);

// where jsonInString is your json {"userId":"1","userName":"Yasir"}

Comments

4
Gson gson = new Gson();
User user = gson.fromJson("{\"userId\":\"1\",\"userName\":\"Yasir\"}", User.class);

Comments

1
Gson gson = new Gson();

User u=gson.fromJson(jsonstring, User.class);
System.out.println("userName: "+u.getusername);  

Comments