25

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
  • 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

60

Try this:

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

// where jsonInString is your json {"userId":"1","userName":"Yasir"}
Jekin Kalariya
  • 3,375
  • 2
  • 19
  • 32
4
Gson gson = new Gson();
User user = gson.fromJson("{\"userId\":\"1\",\"userName\":\"Yasir\"}", User.class));
dtenreiro
  • 128
  • 5
1
Gson gson = new Gson();

User u=gson.fromJson(jsonstring, User.class);
System.out.println("userName: "+u.getusername);  
Ravindra Kushwaha
  • 7,428
  • 13
  • 49
  • 95