AKB
AKB

Reputation: 5938

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?

Upvotes: 0

Views: 1753

Answers (3)

user3487063
user3487063

Reputation: 3692

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

Upvotes: 2

Miguel Prz
Miguel Prz

Reputation: 13792

The GSON library is very easy for this kind of tasks

Upvotes: 1

Charles Smartt
Charles Smartt

Reputation: 349

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.

Upvotes: 0

Related Questions