31

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

  • 1
    User user=new Gson().fromJson(yourJsonString,User.class); – Abdul Rizwan Sep 28 '17 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 http://pojo.sodhanalibrary.com/ . So you can just drop those POJOS into your project and still use the top answer. saves time and typos. – Paul Nov 09 '17 at 14:13

4 Answers4

70

Try this:

Gson gson = new Gson();
String jsonInString = "{\"userId\":\"1\",\"userName\":\"Yasir\"}";
User user= gson.fromJson(jsonInString, User.class);
Sándor Juhos
  • 1,535
  • 1
  • 12
  • 19
7
User user= gson.fromJson(jsonInString, User.class);

// where jsonInString is your json {"userId":"1","userName":"Yasir"}
Jekin Kalariya
  • 3,475
  • 2
  • 20
  • 32
4
Gson gson = new Gson();
User user = gson.fromJson("{\"userId\":\"1\",\"userName\":\"Yasir\"}", User.class);
Sudhanshu Gaur
  • 7,486
  • 9
  • 47
  • 94
dtenreiro
  • 168
  • 5
1
Gson gson = new Gson();

User u=gson.fromJson(jsonstring, User.class);
System.out.println("userName: "+u.getusername);  
Ravindra Kushwaha
  • 7,846
  • 14
  • 53
  • 103