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

ss2ws0br  于 2022-11-06  发布在  Java
关注(0)|答案(4)|浏览(156)

此问题在此处已有答案

Parse JSON file using GSON(3个答案)
六年前就关门了。
假设我有json字符串

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

现在我有一个类User

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

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

ht4b089n

ht4b089n1#

试试看:

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

41zrol4v2#

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

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

dzhpxtsq3#

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

e0bqpujr4#

Gson gson = new Gson();

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

相关问题