gpt4 book ai didi

java - 正确输入解析json

转载 作者:行者123 更新时间:2023-11-30 02:08:42 25 4
gpt4 key购买 nike

解析 json 响应时,其中一个键可以是字符串“value”或 null。我将响应解析为:

  @JsonInclude(JsonInclude.Include.NON_NULL)
@JsonPropertyOrder({
"status",
"code",
"exception"
})

public class Response {

private String status;
private long code;
private String exception;


public String getStatus() {
return status;
}

public void setStatus(String status) {
this.status = status;
}


public long getCode() {
return code;
}

public void setCode(long code) {
this.code = code;
}


public String getException() {
return exception;
}

public void setException(String exception) {
this.exception = exception;
}

当我得到 null 时,我有错误。我怎样才能正确地做到这一点?

我尝试@JsonInclude(JsonInclude.Include.NON_NULL),但它不起作用

public class JsonParserResponse  throws UnsupportedEncodingException, JsonParseException, IOException {
Response resp= new Response();
try{
JSONObject outerObject = new JSONObject({"status":null,"code":0,"exception":""} );
resp.setStatus(outerObject.getString("status")); System.out.printf("name=%s , value=%s\n", "status", outerObject.getString("status"));
resp.setCode(outerObject.getInt("code")); System.out.printf("name=%s , value=%s\n", "code",outerObject.getInt("code"));
resp.setException(outerObject.getString("exception")); System.out.printf("name=%s , value=%s\n","exception" ,outerObject.getString("exception"));
}catch(Exception e) {
e.printStackTrace();
}

我有错误^

JSONObject["status"] not a string.
at org.json.JSONObject.getString(JSONObject.java:639)
at ru.JsonParserResponse.parseResult(JsonParserResponse.java:161)
at ru.JsonParserResponse.main(JsonParserResponse.java:74)

最佳答案

这会有所帮助

在 Response 类上添加 @JsonIgnoreProperties(ignoreUnknown =true),这将忽略空值 (com.fasterxml.jackson.annotation。)

当变量名称与 JsonProperty 相同时,无需使用 JsonProperty

关于java - 正确输入解析json,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50718334/

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