简体   繁体   English

如何读取java中的JSON文件作为下面给定JSON的键值对?

[英]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();
    }
}

Your parsing is more or less correct depending on JSON that I would not read. 根据我不会阅读的JSON,您的解析或多或少是正确的。 Only mistake is that companyList is JSONArray and it's elements are of Object type. 唯一的错误是companyList是JSONArray并且它的元素是Object类型。 You need to externally cast it to JSONObject and then get your model out of it. 您需要从外部将其转换为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.

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