正确输入解析json

时间:2018-06-06 10:39:32

标签: java json parsing

解析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)

3 个答案:

答案 0 :(得分:1)

这将有助于

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

当您的变量名与JsonProperty

相同时,无需使用JsonProperty

答案 1 :(得分:1)

此代码应该有效(看起来你的json格式错误):

    String json = "{\"status\":null,\"code\":0,\"exception\":\"\"}";

    JSONObject outerObject = new JSONObject(json); 

    Response resp = new Response();

    resp.setStatus(outerObject.getString("status"));
    resp.setCode(outerObject.getInt("code"));
    resp.setException(outerObject.getString("exception"));

答案 2 :(得分:0)

import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonInclude.Include;

@JsonInclude(Include.NON_NULL)
在你的课堂上试一试希望这对你有帮助。

@JsonInclude(Include.NON_NULL)
公共课回复{
    //代码.....
}