简体   繁体   English

使用 Gson 解析 json 数组

[英]json Array Parsing using Gson

i have the following Json Response as :我有以下 Json 响应:

{"StatusCode":2,"Error_fields":[{"user":"XXX"},{"password":"YYY"}]}, and i have to parse that response using Gson, so i have built the ResponseBase class as following : {"StatusCode":2,"Error_fields":[{"user":"XXX"},{"password":"YYY"}]},我必须使用 Gson 解析该响应,所以我构建了 ResponseBase类如下:

BaseResponse.java基响应文件

    @SerializedName("StatusCode")
    private int StatusCode;

    @SerializedName("Error_fields")
    List<ErrorField> Erro;

    public void setStatusCode(int statusCode){
        this.StatusCode=statusCode;
    }

    public int getStatusCode(){
        return this.StatusCode;
    }

    public List <ErrorField> getErro() {
        return Erro;
    }

    public void setErro(List <ErrorField> erro) {
        Erro = erro;
    }

and Also i have added the Error Fields as : ErrorField.java而且我还添加了错误字段:ErrorField.java

public class ErrorField {

    String ErrorTitle;

    String ErrorMessage;

    public String getErrorTitle() {
        return ErrorTitle;
    }

    public void setErrorTitle(String errorTitle) {
        ErrorTitle = errorTitle;
    }

    public String getErrorMessage() {
        return ErrorMessage;
    }

    public void setErrorMessage(String errorMessage) {
        ErrorMessage = errorMessage;
    }
}

so in order , to receive the json array correctly , i have to add annotation to ErrorTitle to be :因此,为了正确接收 json 数组,我必须向 ErrorTitle 添加注释:

@SerializedName("password")
    String ErrorTitle;

so in case of i don't know the returned json object key's it will fail , and it's not a good solution to add all the suggested annotation to expect is it existed or not , also i have tried to make that List<ErrorField> as List<JsonObject> and the same results it returns empty value , but it counts "2" as the Array size !?因此,如果我不知道返回的 json 对象键,它将失败,并且添加所有建议的注释以期望它是否存在并不是一个好的解决方案,我也尝试将List<ErrorField>设为List<JsonObject>和相同的结果它返回空值,但它计算“2”作为数组大小!?

problem solved by changing the List<ErroField> into通过将List<ErroField>更改为解决的问题

List<Map<String,String>> Errro;

and it's working with a dynamic range of returned json objects without depend on the key's并且它正在处理返回的 json 对象的动态范围,而不依赖于键的

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM