[英]how to read the JSON file in java as key value pair for below given JSON?
{ "XML": { "version": 1.0, "encoding": "UTF-8" }, "Comment": "ABC EFG Json", "pCt": { "pCHead": { "Date": "9999-12-31", "ID ": "12345 ", "Type": "ABC", "prtList": [{ "cCType": "B", "cReason": "", "oInd": 10, }], "pNet": [{ "seType": "3", "eDate": "2016-10-01", "exDate": "9999-12-31", }] } } }
public static void main(String[] args) {
JSONParser parser = new JSONParser();
System.out.println("hii");
try {
Object obj = parser.parse(new FileReader("D:\\TestJson.txt"));
JSONObject jsonObject = (JSONObject) obj;
Object pCt = jsonObject.get("pCt");
String author = (String) jsonObject.get("pCHead");
JSONArray companyList = (JSONArray) jsonObject.get("prtList");
System.out.println("Name: " + pCt);
System.out.println("\nCompany List:"+author);
System.out.println("\nCompany List:");
Iterator<String> iterator = companyList.iterator();
while (iterator.hasNext()) {
System.out.println(iterator.next());
}
} catch (Exception e) {
e.printStackTrace();
}
}
根據我不會閱讀的JSON,您的解析或多或少是正確的。 唯一的錯誤是companyList是JSONArray並且它的元素是Object類型。 您需要從外部將其轉換為JSONObject,然后從中獲取模型。
//lombok
@Data
@Builder
@NoArgsConstructor
@AllArgsConstructor
public class Company {
String cCType;
String cReason;
String oInd;
}
//in your main
for(Object o : companyList) {
JSONObject companyJson = (JSONObject) o;
Company company = Company.Builder
.anCompany()
.withCCType(companyJson.get("cCType"))
.withCReason(companyJson.get("cReaeson"))
.withOInd(companyJson.get("oInd"))
.build();
//do whatever you like with data
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.