如何使用Gson将Json转换为Java对象

时间:2016-07-28 12:22:36

标签: java json gson

假设我有json字符串

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

现在我有一个用户类

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

现在如何将上面的json字符串转换为用户类对象

4 个答案:

答案 0 :(得分:40)

试试这个:

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

答案 1 :(得分:5)

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

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

答案 2 :(得分:2)

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

答案 3 :(得分:0)

Gson gson = new Gson();

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