OPK
OPK

Reputation: 4180

Paring json string in java with javax.json

My ajax passed a json array that looks like this:

 {"formData":[{"cusID":"2"},{"empID":"1"}],"invoice":578416969}

I am trying to get the data using javax.json library.

JSONObject jsonObj = new JSONObject(jasonString);

I am able to grab the value of invoice:

Integer invoiceNum = (Integer) jsonObj.get("invoice");

But I am unable to grab the value of cusID and empID, by doing the following:

Integer cusId = Integer.parseInt((String) jsonObj.get("cusID"));
Integer empId = Integer.parseInt((String) jsonObj.get("empID"));

Error message:org.json.JSONException: JSONObject["cusID"] not found.

What did I do wrong? I am open to suggestions,if you have a better way of handling this json data, I am willing to use it.

Upvotes: 0

Views: 122

Answers (3)

suhyunjeon
suhyunjeon

Reputation: 161

You can using Gson() library. (com.google.gson.Gson) It makes you simple.

 JsonArray formData = jsonElement.getAsJsonObject().get("formData").getAsJsonArray();
 Integer cusId = formData.get(0).getAsJsonObject().get("cusID").getAsInt();
 Integer empId = formData.get(1).getAsJsonObject().get("empID").getAsInt();

Upvotes: 0

alcfeoh
alcfeoh

Reputation: 2267

cusID is actually an attribute of the first object in the array formData:

jsonObj.getJsonArray("formData").getJsonObject(0).get("cusID");

should do the trick.

Upvotes: 1

AnatolyS
AnatolyS

Reputation: 4319

First you have to get formData as an array, after that get the first element and get custId, after that get the second element and get empID.

Upvotes: 0

Related Questions