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

2022-09-01 18:06:00

假设我有 json 字符串

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

现在我有一个类用户

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

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


答案 1

试试这个:

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

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

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