猿问

将包含对象数组的 JSON 转换为正确的 Java 对象

我有一个简单的 Spring Boot 项目,其中调度程序定期使用 RESTful API 并转换传入的 JSON 文件。


JSON 文件实际上是具有一些键和值的对象数组:


[

{"CoID":1,"CoName":"کشاورزی و دامپروری مگسال","CoNameEnglish":"MagsalAgriculture & Animal Husbandry Co.","CompanySymbol":"MAGS","CoTSESymbol":"زمگسا","GroupID":1,"GroupName":"كشاورزی و دامپروری","IndustryID":1,"IndustryName":"كشاورزی، دامپروری و خدمات وابسته به آن","InstCode":"5054819322815158","TseCIsinCode":"IRO1MAGS0006","TseSIsinCode":"IRO1MAGS0001","MarketID":1,"MarketName":"بورس"},

...

]

我有一个名为的类,其Company字段与 JSON 文件中数组中的对象之一类似:


@JsonIgnoreProperties(ignoreUnknown = true)

public class Company {


private int CoID;

private String CoName;

private String CoNameEnglish;

private String CompanySymbl;

private String CoTSESymbl;

private int GroupID;

private String GroupName;

private int IndustryID;

private String IndustryName;

private String IndustryCode;

private String TseCIsinCode;

private String TseSIsinCode;

private int MarketID;

private String MarketName;

    // And proper getters, setters and constructor //

我还创建了一个名为的包装类CompanyList:


public class CompanyList {


private ArrayList<Company> companyList;


public ArrayList<Company> getCompanyList() {

    return companyList;

}


public void setCompanyList(ArrayList<Company> companyList) {

    this.companyList = companyList;

}


public CompanyList() {


}


@Override

public String toString() {

    return "CompanyList [companyList=" + companyList + "]";

}

}


德玛西亚99
浏览 98回答 1
1回答

SMILET

第二种和第三种方法应该可以正常工作。您需要检查您的 json 响应结构。您可以使用以下 json 进行测试(它们适用于您的代码):第二种方法:[{"tseCIsinCode":null,"tseSIsinCode":null,"coName":"n1","industryID":0,"coID":0,"coNameEnglish":null,"companySymbl":null,"coTSESymbl":null,"groupID":0,"groupName":null,"industryName":null,"industryCode":null,"marketID":0,"marketName":null},{"tseCIsinCode":null,"tseSIsinCode":null,"coName":"n2","industryID":0,"coID":0,"coNameEnglish":null,"companySymbl":null,"coTSESymbl":null,"groupID":0,"groupName":null,"industryName":null,"industryCode":null,"marketID":0,"marketName":null}]第三:{"companyList":[{"coName":"n1","coID":0,"coNameEnglish":null,"companySymbl":null,"coTSESymbl":null,"groupID":0,"groupName":null,"industryID":0,"industryName":null,"industryCode":null,"tseCIsinCode":null,"tseSIsinCode":null,"marketID":0,"marketName":null},{"coName":"n2","coID":0,"coNameEnglish":null,"companySymbl":null,"coTSESymbl":null,"groupID":0,"groupName":null,"industryID":0,"industryName":null,"industryCode":null,"tseCIsinCode":null,"tseSIsinCode":null,"marketID":0,"marketName":null}]}更新:第二种方法修复:更改 json 字段名称 -“CoName”->“coName”、“CoID”->“coID”等。更改后它将完美运行。第三种方法修复:用第二种方法包装你的 json"{\"companyList\":[...]&nbsp;并更改字段名称第二次更新&nbsp;如果您无法更改响应中的 json。您可以在 Company 类中使用映射@JsonProperty("CoName") private&nbsp;String&nbsp;CoName;
随时随地看视频慕课网APP

相关分类

Java
我要回答