【问题标题】:Parse json response using GSON in reterofit在改造中使用 GSON 解析 json 响应
【发布时间】:2016-09-09 05:32:04
【问题描述】:

我已使用改造 sdk 进行 api 调用。我有 GSON sdk 用于解析响应。我有一些难以解析的 json 响应。我已经在下面发布了要解析的json响应。我需要获取地址行arraylist。

我正在从列表中获取空数据。

{
    "QA": {
        "CreditsUsed": 1,
        "State": "Results"
    },
    "SearchResult": {
        "VerifyLevel": "Verified",
        "Address": {
            "AddressLine": [{
                "LineContent": "None",
                "Label": {},
                "Line": "2500Kearney St"
            }, {
                "LineContent": "None",
                "Label": {},
                "Line": {}
            }, {
                "LineContent": "None",
                "Label": {},
                "Line": {}
            }, {
                "Label": "City name",
                "Line": "Springfield"
            }, {
                "Label": "State code",
                "Line": "MO"
            }, {
                "Label": {},
                "Line": "65803-5048"
            }, {
                "Label": "Country",
                "Line": "UNITED STATES OF AMERICA"
            }],
            "DPVStatus": "DPVNotConfigured"
        },
        "VerificationFlags": {
            "StateProvinceChanged": true,
            "PostCodeCorrected": true
        }
    }
}

模型类

public class DineshValues {

    String Country;
    String Search;
    @SerializedName("LineContent")
    String LineContent;
    @SerializedName("Line")
    String Line;
    @SerializedName("AddressLine")
    List<AddressLine> data=new ArrayList();

    public List<AddressLine> getData() {
        return data;
    }

    public String getLineContent() {
        return LineContent;
    }

    public void setLineContent(String lineContent) {
        LineContent = lineContent;
    }

    public String getLine() {
        return Line;
    }

    public void setLine(String line) {
        Line = line;
    }

    public void setData(List<AddressLine> data) {
        this.data = data;
    }
    public String getCountry() {
        return Country;
    }

    public void setCountry(String country) {
        Country = country;
    }

    public String getSearch() {
        return Search;
    }

    public void setSearch(String search) {
        Search = search;
    }
 }

AddressLine 类文件

public class AddressLine {

@SerializedName("LineContent")
@Expose
private String lineContent;
@SerializedName("Label")
@Expose
private String label;
@SerializedName("Line")
@Expose
private String line;

/**
* 
* @return
* The lineContent
*/
public String getLineContent() {
return lineContent;
}

/**
* 
* @param lineContent
* The LineContent
*/
public void setLineContent(String lineContent) {
this.lineContent = lineContent;
}

/**
* 
* @return
* The label
*/
public String getLabel() {
return label;
}

/**
* 
* @param label
* The Label
*/
public void setLabel(String label) {
this.label = label;
}

/**
* 
* @return
* The line
*/
public String getLine() {
return line;
}

/**
* 
* @param line
* The Line
*/
public void setLine(String line) {
this.line = line;
}

这样称呼

RetrofitRest.getClient().getLogin("1111111" ,obj,new Callback<DineshValues >() {

  @Override
        public void success(DineshValues arg0, Response arg1) {
            // TODO Auto-generated method stub
            Log.e("size",arg0.getData+"");
        }
}

【问题讨论】:

  • 你有什么异常吗?如果是,请编辑问题并添加完整的 logcat 报告。我猜当您尝试打印 arg0.getData 时,它正在打印对象地址。在 AddressLine 覆盖 toString 方法中做一件事。或者去 arg0.getData.get(0).getLineContent()
  • 09-09 05:54:53.515: E/AndroidRuntime(1411): java.lang.IndexOutOfBoundsException: Invalid index 0, size is 0 我在使用 arg0.getData.get( 0).getLineContent().
  • 我认为我在为给定的响应创建 pojo 类方面做错了......你能检查我的 pojo 类吗?
  • edit有异常消息的问题
  • 每个 Label 和 Line 属性都不是字符串,它们是对象,如 {} 所述。你确定你的 Java 类是正确的吗?

标签: android json gson retrofit


【解决方案1】:

请尝试以下 POJO,

地址

public class Address {

    @SerializedName("AddressLine")
    private List<AddressLine> addressLine = new ArrayList<AddressLine>();
    @SerializedName("DPVStatus")
    private String dPVStatus;

    /**
     * 
     * @return
     *     The addressLine
     */
    public List<AddressLine> getAddressLine() {
        return addressLine;
    }

    /**
     * 
     * @param addressLine
     *     The AddressLine
     */
    public void setAddressLine(List<AddressLine> addressLine) {
        this.addressLine = addressLine;
    }

    /**
     * 
     * @return
     *     The dPVStatus
     */
    public String getDPVStatus() {
        return dPVStatus;
    }

    /**
     * 
     * @param dPVStatus
     *     The DPVStatus
     */
    public void setDPVStatus(String dPVStatus) {
        this.dPVStatus = dPVStatus;
    }

}

地址线

public class AddressLine {

    @SerializedName("LineContent")
    private String lineContent;
    @SerializedName("Label")
    private String label;
    @SerializedName("Line")
    private String line;

    /**
     * 
     * @return
     *     The lineContent
     */
    public String getLineContent() {
        return lineContent;
    }

    /**
     * 
     * @param lineContent
     *     The LineContent
     */
    public void setLineContent(String lineContent) {
        this.lineContent = lineContent;
    }

    /**
     * 
     * @return
     *     The label
     */  
    public String getLabel() {
        return label;
    }

    /**
     * 
     * @param label
     *     The Label
     */
    public void setLabel(String label) {
        this.label = label;
    }

    /**
     * 
     * @return
     *     The line
     */
    public String getLine() {
        return line;
    }

    /**
     * 
     * @param line
     *     The Line
     */
    public void setLine(String line) {
        this.line = line;
    }

}

数据

public class Data {

    @SerializedName("QA")
    private QA qA;
    @SerializedName("SearchResult")
    private SearchResult searchResult;

    /**
     * 
     * @return
     *     The qA
     */  
    public QA getQA() {
        return qA;
    }

    /**
     * 
     * @param qA
     *     The QA
     */   
    public void setQA(QA qA) {
        this.qA = qA;
    }

    /**
     * 
     * @return
     *     The searchResult
     */   
    public SearchResult getSearchResult() {
        return searchResult;
    }

    /**
     * 
     * @param searchResult
     *     The SearchResult
     */   
    public void setSearchResult(SearchResult searchResult) {
        this.searchResult = searchResult;
    }

}

质量检查

public class QA {

    @SerializedName("CreditsUsed")
    private Long creditsUsed;
    @SerializedName("State")
    private String state;

    /**
     * 
     * @return
     *     The creditsUsed
     */
    public Long getCreditsUsed() {
        return creditsUsed;
    }

    /**
     * 
     * @param creditsUsed
     *     The CreditsUsed
     */   
    public void setCreditsUsed(Long creditsUsed) {
        this.creditsUsed = creditsUsed;
    }

    /**
     * 
     * @return
     *     The state
     */   
    public String getState() {
        return state;
    }

    /**
     * 
     * @param state
     *     The State
     */   
    public void setState(String state) {
        this.state = state;
    }

}

搜索结果

public class SearchResult {

    @SerializedName("VerifyLevel")
    private String verifyLevel;
    @SerializedName("Address")
    private Address address;
    @SerializedName("VerificationFlags")
    private VerificationFlags verificationFlags;

    /**
     * 
     * @return
     *     The verifyLevel
     */   
    public String getVerifyLevel() {
        return verifyLevel;
    }

    /**
     * 
     * @param verifyLevel
     *     The VerifyLevel
     */   
    public void setVerifyLevel(String verifyLevel) {
        this.verifyLevel = verifyLevel;
    }

    /**
     * 
     * @return
     *     The address
     */   
    public Address getAddress() {
        return address;
    }

    /**
     * 
     * @param address
     *     The Address
     */
    public void setAddress(Address address) {
        this.address = address;
    }

    /**
     * 
     * @return
     *     The verificationFlags
     */   
    public VerificationFlags getVerificationFlags() {
        return verificationFlags;
    }

    /**
     * 
     * @param verificationFlags
     *     The VerificationFlags
     */  
    public void setVerificationFlags(VerificationFlags verificationFlags) {
        this.verificationFlags = verificationFlags;
    }

}

验证标志

public class VerificationFlags {

    @SerializedName("StateProvinceChanged")
    private Boolean stateProvinceChanged;
    @SerializedName("PostCodeCorrected")
    private Boolean postCodeCorrected;

    /**
     * 
     * @return
     *     The stateProvinceChanged
     */   
    public Boolean getStateProvinceChanged() {
        return stateProvinceChanged;
    }

    /**
     * 
     * @param stateProvinceChanged
     *     The StateProvinceChanged
     */   
    public void setStateProvinceChanged(Boolean stateProvinceChanged) {
        this.stateProvinceChanged = stateProvinceChanged;
    }

    /**
     * 
     * @return
     *     The postCodeCorrected
     */   
    public Boolean getPostCodeCorrected() {
        return postCodeCorrected;
    }

    /**
     * 
     * @param postCodeCorrected
     *     The PostCodeCorrected
     */  
    public void setPostCodeCorrected(Boolean postCodeCorrected) {
        this.postCodeCorrected = postCodeCorrected;
    }

}

改造电话

RetrofitRest.getClient().getLogin("your text", obj, new Callback<Data>() {
            @Override
            public void success(Data data, Response response) {
                SearchResult searchResult = data.getSearchResult();
                if (searchResult != null) {
                    Address address = searchResult.getAddress();
                    if (address != null && address.getAddressLine() != null) {
                        for (AddressLine addressLine : address.getAddressLine()) {
                            Log.d("TAG", "addressLine" + addressLine);
                        }
                    }
                }
            }
        });

【讨论】:

  • 我尝试了所有这些东西..但我仍然在数据对象上得到空值... public void success(Data data, Response response) {
  • 字符串国家;字符串搜索;公共字符串 getCountry() { 返回国家; } public void setCountry(String country) { Country = country; } 公共字符串 getSearch() { 返回搜索; } 公共无效 setSearch(字符串搜索){ 搜索 = 搜索; } 数据 obj=新数据(); obj.setCountry("新泽西州"); obj.setSearch("@2500 East Kearney Street,@,@,@Springfield,@MO,@65803");
  • 我在 Data 类中添加了这些行,用于将 post 参数传递给 reterofit
  • 您是否使用任何 REST 客户端插件(邮递员、Restclient 等)测试了 API 请求/响应?请确保您得到正确的 JSON 响应
【解决方案2】:

我已经纠正了它有多余“,”的json,如下所示。

"StateTransition":"SearchResults",

在解析 http://www.jsoneditoronline.org/ 中的 json 时。我注意到在您的 jsonObject 中,您还有 2 个带有键“CAB”和“Result”的 jsonObject。在您的第二个 jsonObject 中,您有另一个带有“Address”键的 jsonObject,其中有“AddressLine”数组。

所以请纠正完整的 pojo DineshValues。 如果您需要任何进一步的帮助,请告诉我,我将添加完整的 POJO

更新
解决方案 1 -
正如评论中提到的,您使用 jsonschema2pojo 生成 pojo,您可以保留那些可能只是代码的类并使用以下行来提取地址

List<AddressLine> addressLine = arg0.getResult().getAddress().getAddressLine()

现在迭代 addressLine 并提取您需要的数据。

注意 - 1) 确保 arg0 是根 JsonObject 的类型类。
2) cricket_007 提到的另一点 - 每个标签和线 属性不是字符串,它们是对象,如 {} 所述。


解决方案 2 -
您只能在项目中保留生成的类文件中的 AddressLine 类,并使用以下行来提取地址。

RetrofitRest.getClient().getLogin("1111111" ,obj,new Callback<DineshValues >() {

  @Override
        public void success(String arg0, Response arg1) {
            // TODO Auto-generated method stub
            JsonObject rootJsonObject = new JsonObject(arg0);
            JsonObject searchResultJsonObject = rootJsonObject.getJsonObject("SearchResult");
            JsonObject addressJsonObject = searchResultJsonObject.getJsonObject("Address")

            Type listType = new TypeToken<List<AddressLine>>(){}.getType();
            List<AddressLine> addressLineList = gson.fromJson(addressJsonObject, listType);
            //Now iterate the addressLineList to get the address
             Log.e("size",addressLineList.getSize+"");

        }
}

【讨论】:

  • @cricket_007 完全同意你的看法。最初我想将其添加为评论。所以我使用了标签。感谢您编辑它。
  • 我已经给出了完整的回复......我必须得到(AddressLine)数组列表......我怎样才能得到这个......提供实现它的步骤
  • 为给定的响应提供 pojo 类。我使用 (jsonschema2pojo.org) 来生成 pojo..但我生成了很多类。但我只需要地址值
  • @DineshkumarArunachalam 请检查更新的答案。
猜你喜欢
  • 1970-01-01
  • 2016-02-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-04-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多