简体   繁体   中英

How to parse JSON records which have JSON array elements in it?

I am getting the error:

JSONObject["Transaction_details"] not found.

Why is it not able to find Transaction_details ?

Code:

for(Iterator it = mapper.readValues(new JsonFactory().createJsonParser(in),JSONObject.class);it.hasNext();)
{
    JSONObject js = (JSONObject) it.next();
    JSONArray recs = (JSONArray) js.get("Transaction_details");         
    for (int i = 1; i < recs.length(); ++i) {
        JSONObject rec = recs.getJSONObject(i);
        int id = rec.getInt("merchantid");
        String loc = rec.getString("transaction_amount");

}

Snapshot of a part of my schema:

 {
    "name" : "cica",
    "type" : "long"
  }, {
    "name" : "pica",
    "type" : "long"
  }, {
    "name" : "issuingcountry",
    "type" : "string"
  }, {
    "name" : "Transaction_details",
    "type" : {
      "type" : "array",
      "items" : {
        "type" : "record",
        "name" : "Transaction_details",
        "doc" : "Transaction event details",
        "fields" : [ {
          "name" : "transactionid",
          "type" : "long"
        }, {
          "name" : "transactiondate",
          "type" : "string"
        }, {
          "name" : "Productcode",
          "type" : "string"
           }
]
}

Something like the below snippet should work. But, I have not compiled or executed it. Basically, you would have to check if you are encountering a "Transaction_details" name value. If yes, then you need to retrieve its 'type' array and work with its elements. Hope this helps!

for(Iterator it = mapper.readValues(new JsonFactory().createJsonParser(in),JSONObject.class);it.hasNext();)
{
    JSONObject js = (JSONObject) it.next();
    String nameValue = (String) js.get("name");
    if ("Transaction_details".equals(nameValue)) {
       JSONArray recs = (JSONArray) js.get("type");
       for (int i = 1; i < recs.length(); ++i) {
           JSONObject rec = recs.getJSONObject(i);
            ...
       }
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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