gpt4 book ai didi

java - 如何对Java对象进行正确的Json反序列化?

转载 作者:行者123 更新时间:2023-12-01 09:59:44 26 4
gpt4 key购买 nike

我真的需要帮助,我正在反序列化下一个 json:

{
"name":"myname",
"userID":"12345",
"password":"sha1passwordASDESFSGSD",
"active":"1",
"profile":"2",
"job":"Manager"
}

我使用 Jersey 来创建 webService,当我接收 json 时,我将它作为输入流接收

我也尝试过使用字符串

@POST
@Path("user/in/")
@Produces("application/json")
public String InsertUser(InputStream inStr)
{
String line = null, res = "POST 200 > ";
BufferedReader br = new BufferedReader(new InputStreamReader(inStr));
try {
while ((line = br.readLine()) != null) {
System.out.println(line);
res += line;
}
} catch (IOException e) {
e.printStackTrace();
}

try {
UserInformation user = new Gson().fromJson(res, UserInformation.class);
System.out.println("All done");
System.out.println(user.getName());

} catch (Exception e) {
System.out.println("Error al convertir jo object " + e.getCause() + e.getMessage());
}

return "POST 200 > ";
}

我尝试使用InputStreamReader:

@POST
@Path("user/in/")
@Produces("application/json")
public String InsertUser(InputStream inStr)
{
try {
InputStreamReader isr = new InputStreamReader(inStr);
UserInformation user = new Gson().fromJson(isr, UserInformation.class);
System.out.println("All done");

System.out.println(user.getName());

} catch (Exception e) {
System.out.println("Error al convertir jo object " + e.getCause() + e.getMessage());
}

return "POST 200 > ";
}

这些代码都不起作用。他们不会抛出异常或打印“全部完成”。
当我调试对象时,user 不会出现在变量菜单中。
根据我的经验,是因为 UserInformation user = new Gson().fromJson(isr, UserInformation.class);

行中发生错误

但我看不出是哪一个。

我的 UserInformation 类是下一个

public class UserInformation {

private String name;
private String userID;
private String password;
private String active;
private String profile;
private String job;

// Methods removed for brevity
}

最佳答案

我假设您正在使用 Google gson。这是我的回答:

    @Post
@Path("user/in")
@Produces(MediaType.APPLICATION_JSON)
public Response InsertUser(string json){
JsonElement jsonElement = new JsonParser().parse(json);
JsonObject object = jsonElement.getAsJsonObject();
String name = object.getAsJsonPrimitive("name").getAsString();
int userID = object.getAsJsonPrimitve("userID").getAsInt();
String password = object.getAsJsonPrimitive("password").getAsString();
String job = object.getAsJsonPrimitive("job").getAsString();
int active = object.getAsJsonPrimitve("active").getAsInt();
int profile = object.getAsJsonPrimitve("profile").getAsInt();



return Response.status(Response.Status.OK).entity("all done").build();


}

关于java - 如何对Java对象进行正确的Json反序列化?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36897949/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com