简体   繁体   中英

json multiple json data parsing in java

I have a json input like this

[ {
    "Company":"BEG",
    "Account":"1001",
    "Deptid":"",
    "Location":"",
    "Transaction Date":"2014-07-15",
    "Description":"Invoice",
    "Debit":0.0,
    "Credit":13.46,
    "Invoice Nbr":"1682"
    },
    {
    "Company":"BEG2",
    "Account":"1002",
    "Deptid":"23",
    "Location":"NY",
    "Transaction Date":"2014-07-15",
    "Description":"Invoice",
    "Debit":0.0,
    "Credit":13.45,
    "Invoice Nbr":"1682432"
    },
    ....
    ....
    },
    {
    "Company":"BEG99",
    "Account":"1099",
    "Deptid":"",
    "Location":"",
    "Transaction Date":"2014-07-15",
    "Description":"Invoice",
    "Debit":0.0,
    "Credit":13.46,
    "Invoice Nbr":"168243299"
    }]

I am using json simple jar to parse the json. my code is:

public String appendData(String str) throws IOException, ParseException{
        System.out.println("========Inside appendData======"+str);
        JSONParser jsonParser = new JSONParser();
        JSONObject jsonObject = (JSONObject) jsonParser.parse(new StringReader(str));
        double debit = (double) Double.parseDouble(jsonObject.get("Debit").toString());
}

Above code works fine, If i send single lock of data and without [ and ] bracket. Above json is a valid json according to JSONLint

Question:

1) How do I parse above json having multiple data?

Something like below for your scenario, if you want to use json-simple:

JSONParser jsonParser = new JSONParser();
                Object obj =  jsonParser.parse(new StringReader(str));
            if (obj instanceof JSONObject) {
                JSONObject jo = (JSONObject) obj;
                 System.out.println(jo.get("Debit").toString());
            } else {
                JSONArray ja = (JSONArray) obj;
                for(int i=0;i<ja.size();i++){
                    JSONObject   jsonObject = (JSONObject)ja.get(i);
                    System.out.println(jsonObject.get("Debit").toString());
                }
            }

GSON库对于此类任务非常简单

https://code.google.com/p/json-simple/wiki/DecodingExamples

You'll see that to process your array instead of JSONObject you need to us JSONArray. The link has a full example.

I typically use Jackson for my JSON parsing, it is pretty good.

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