0

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.

3
  • Whats the error message or result?? FYI, I am suspecting that this may have to do with how your casting your variables... Commented Oct 12, 2015 at 18:49
  • @ryekayo updated the OP added error message Commented Oct 12, 2015 at 18:50
  • jsfiddle.net/arunpjohny/wbq4wbd2/1 Commented Oct 13, 2015 at 13:41

3 Answers 3

1

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

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

should do the trick.

Sign up to request clarification or add additional context in comments.

4 Comments

formData is a array of objects
Just edited my answer. Did not test it but this should work.
worked now. Thanks. You are missing a ; in your code btw.
Just added it to make it perfect. Thanks.
0

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.

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.