I'm having a problem reading JSON Array because inside my array, there's another array and I'm confused.Please see my code.
JSONObject jsonObject = JSONFactoryUtil.createJSONObject();
JSONObject obj = JSONFactoryUtil.createJSONObject();
JSONObject jsonObjectReturn = JSONFactoryUtil.createJSONObject();
//JSONOBJECT RETURN
JSONArray array = JSONFactoryUtil.createJSONArray();
for (int i = 0; i < jsonArray.length(); i++) {
obj = jsonArray.getJSONObject(i);
callableStatement = (CallableStatement) conn
.prepareCall("{call TaxpaymentSPv2(?,?,?,?,?,?,?,?)}");
callableStatement.setString(1, obj.getString("rdoCode"));
callableStatement.setString(2, obj.getString("rcoCode"));
callableStatement.setString(3, obj.getString("tpTin"));
callableStatement.setString(4, obj.getString("tpName"));
callableStatement.setString(5, obj.getString("tpAddress"));
callableStatement.setString(6, obj.getString("receiptType"));
callableStatement.registerOutParameter(7, Types.VARCHAR);
callableStatement.registerOutParameter(8, Types.VARCHAR);
callableStatement.executeUpdate();
String rNo = callableStatement.getString(7);
String date = callableStatement.getString(8);
//---->This is my second Array inside my JSON where im having an error <------
String checkArray = obj.getString("checkArray");
JSONArray jsonArrayCheck = JSONFactoryUtil.createJSONArray(stringArray);
JSONArray jsonArray2 = jsonObject.getJSONArray("checkArray");
System.out.println("..........." + jsonArray2);
jsonObjectReturn = JSONFactoryUtil.createJSONObject();
jsonObjectReturn.put("rNo", rNo);
jsonObjectReturn.put("date", date);
array.put(jsonObjectReturn);
}
return array;
Here's my JSON input:
{
"dataArray": [{
"rdoCode": "001",
"rcoCode": "002911",
"tpTin": "200746409",
"tpName": "JOHN DOE",
"tpAddress": "LA CALIFORNIA",
"receiptType":"ROR",
"receiptMode":"AUTO",
"manualReceiptNo":"",
"checkArray":[{
"ptchkNumber": 14546,
"ptchkDate": 2014-01-01,
"ptchkAmount": 5332,
"ptchkStatus": ""
}]
}]
}
I can't parse the "checkArray" object that gives me this error. com.liferay.portal.kernel.json.JSONException: org.json.JSONException: A JSONArray text must start with '[' at 1 [character 2 line 1]. Can someone tell me what to do? Thanks.
You need to change code:
String checkArray = obj.getString("checkArray");
to following code:
JSONArray checkArray = obj.getJSONArray("checkArray");
JSONObject checkObj = checkArray.getJSONObject(0);
int ptchkNumber = checkObj.getInt("ptchkNumber");
because key checkArray is array inside JSON, so you cannot using getString() but getJSONArray() instead.
Update:
To get each object inside array, you can iterate and access each object:
JSONArray checkArray = obj.getJSONArray("checkArray");
JSONObject checkObj;
for (int itemIndex=0, totalObject = checkArray.length(); itemIndex < totalObject; itemIndex++) {
checkObj = checkArray.getJSONObject(itemIndex);
int ptchkNumber = checkObj.getInt("ptchkNumber");
}
Related
I am trying to parse a json but it give me error java lang.string can not be converted to jsonArray. Here is my json and error :
Value {"MemberList":[{"MemberId":1,"FirmId":1,"MemberTypeId":1,
"MemberUserName":"test#example.com", "MemberName":"sth","UpdateDate":"\/Date(1421840040000)\/",
"LastLoginDate":"\/Date(1454995980000)\/",
"FirmTypeId":1,"FirmName":"Firm","FirmOfficialName":"Firm",
"FirmRowGuid":"sth","MemberRowGuid":"sth","AuthToken":"sth",
"IsRegistered":1}],"MemberPageList":null,"FirmModuleList":null,"Status":true,
"StatusCode":"OK"} of type java.lang.String cannot be converted to JSONArray
When i deleted MemberList header and run manually it works fine but i must parse it with header how should i parse it. userDetail is my json string:
JSONArray jsonArray = new JSONArray(userDetail);
member = new Member();
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObject = jsonArray.getJSONObject(i);
member.MemberId = jsonObject.optInt("MemberId");
member.MemberTypeId = jsonObject.optInt("MemberTypeId");
member.FirmTypeId = jsonObject.optInt("FirmTypeId");
member.IsRegistered = jsonObject.optInt("IsRegistered");
member.MemberUserName = jsonObject.optString("MemberUserName");
member.MemberName = jsonObject.optString("MemberName");
member.UpdateDate = jsonObject.optString("UpdateDate");
member.LastLoginDate = jsonObject.optString("LastLoginDate");
member.FirmName = jsonObject.optString("FirmName");
member.FirmOfficialName = jsonObject.optString("FirmOfficialName");
member.FirmRowGuid = jsonObject.optString("FirmRowGuid");
member.MemberRowGuid = jsonObject.optString("MemberRowGuid");
member.AuthToken = jsonObject.optString("AuthToken");
}
Its a json object not array so change,
JSONArray jsonArray = new JSONArray(userDetail);
to
JSONObject jsonObj= new JSONObject(userDetail);
JSONArray jsonArray = jsonObj.getJSONArray("MemberList");
To manually check json use this http://jsoneditoronline.org/
CODE:
JSONObject jsonObj= new JSONObject(userDetail);
JSONArray jsonArray = jsonObj.getJSONArray("MemberList");
for (int i = 0; i < jsonArray.length(); i++) {
member = new Member();
JSONObject jsonObject = jsonArray.getJSONObject(i);
member.MemberId = jsonObject.optInt("MemberId");
member.MemberTypeId = jsonObject.optInt("MemberTypeId");
member.FirmTypeId = jsonObject.optInt("FirmTypeId");
member.IsRegistered = jsonObject.optInt("IsRegistered");
member.MemberUserName = jsonObject.optString("MemberUserName");
member.MemberName = jsonObject.optString("MemberName");
member.UpdateDate = jsonObject.optString("UpdateDate");
member.LastLoginDate = jsonObject.optString("LastLoginDate");
member.FirmName = jsonObject.optString("FirmName");
member.FirmOfficialName = jsonObject.optString("FirmOfficialName");
member.FirmRowGuid = jsonObject.optString("FirmRowGuid");
member.MemberRowGuid = jsonObject.optString("MemberRowGuid");
member.AuthToken = jsonObject.optString("AuthToken");
}
{
"MemberList": [{
"MemberId": 1,
"FirmId": 1,
"MemberTypeId": 1,
"MemberUserName": "test#example.com",
"MemberName": "sth",
"UpdateDate": "\/Date(1421840040000)\/",
"LastLoginDate": "\/Date(1454995980000)\/",
"FirmTypeId": 1,
"FirmName": "Firm",
"FirmOfficialName": "Firm",
"FirmRowGuid": "sth",
"MemberRowGuid": "sth",
"AuthToken": "sth",
"IsRegistered": 1
}],
"MemberPageList": null,
"FirmModuleList": null,
"Status": true,
"StatusCode": "OK"
}
as you can see the top root data we are getting as an object, within this object we are getting array of "MemberList", so you need to get object first then array inside of it.
and also do this to convert response in to String
HttpResponse response=client.execute(post);
String obj= EntityUtils.toString(response.getEntity());
then use it as you want.
Hope you got this.
i'm trying to parse this JSON code
{
"resultCode":"350",
"message":"OK",
"result":1,
"data":
{
"totalCount":"2",
"videos":[
{
"videoId":"73bfedf534",
"VideoUrl":"www.videourlexample.com",
"title":"vbsample1",
"description":""
},
{
"videoId":"73bfedf534",
"VideoUrl":"www.videourlexample.com",
"title":"vbsample2",
"description":""
}
]
}
}
I was able to parse only this.
"resultCode":"350",
"message":"OK",
"result":1,
this is the java code
JSONObject jsonObject = (JSONObject)
//return the JSON code above.
jsonParser.parse(getHTML("...httpRequest..."));
// get a String from the JSON object
String resultCode = (String) jsonObject.get("resultCode");
System.out.println("[RESULTCODE] The message is: " + resultCode);
// get a String from the JSON object
String message = (String) jsonObject.get("message");
System.out.println("[MESSAGE] The message is: " + message);
// get a number from the JSON object
long result = (long) jsonObject.get("result");
System.out.println("[RESULT] The resultCode is: " + result);
I can't parse the "data". Someone can help me?
I would like to take each value from the json array separately... like resultCode, message and result.
Thank you.
JSONObject mainObj= new JSONObject(yourJSON);
String resultCode= mainObj.get("resultCode");
String message= mainObj.get("message");
String result= mainObj.get("result");
JSONObject dataObj = mainObj.get("data");
JSONArray jsonArray = (JSONArray) dataObj.get("videos");
for (int i = 0; i <jsonArray.length(); i++) {
JSONObject obj= jsonArray.get(i);
String videoId=obj.get("videoId");
String videoUrl=obj.get("VideoUrl");
String title=obj.get("title");
String description=obj.get("description");
System.out.println("videoId="+videoId +"videoUrl="+videoUrl+"title=title"+"description="+description);
}
System.out.println("resultCode"+resultCode+"message"+message+"result"+result);
You can try using this:-
JSONObject dataObj = (JSONObject)dataObj .get("data");
JSONArray jsonArray = (JSONArray) dataObj.get("videos");
for (int i = 0; i <jsonArray.length(); i++) {
System.out.println(((JSONObject)jsonArray.get(i)).get("videoUrl"));
}
Currently I have just printes videoUrl, you can similarly get other attributes for videos.
for data use:
int totalCount = (int) ((Map) jsonObject.get("data")).get("totalCount");
JSONArray videos = (JSONArray) jsonObject.get("data")).get("videos");
and then parse videos JSONArray.
I am new to parsing JSON in java. I have this JSON string:
[
{
"projectId":5,
"userName":"clinician",
"projectName":"r",
"projectSummary":"r",
"projectLanguage":"r",
"contactPersonName":"r",
"contactPersonCV":"r",
"contactPersonEmail":"r",
"contactPersonPhone":"r"
},
[
{
"consentFileId":2,
"projectId":5,
"consentDescription":"r",
"consentFileName":"test.pdf",
"servicePathToGetConsentPdf":null
},
{
"consentFileId":3,
"projectId":5,
"consentDescription":"rrr",
"consentFileName":"test.pdf",
"servicePathToGetConsentPdf":"localhost:8080/4c_viewFile?consentFileId=3"
}
],
[
{
"anonymized_patient_identifier":"r",
"projectId":5
},
{
"anonymized_patient_identifier":"2",
"projectId":5
},
{
"anonymized_patient_identifier":"5",
"projectId":5
}
]
]
I have managed to get values from simpler JSON strings but this one has multiple levels and also there is no key in each level. I tried with simple code like this:
Object obj = parser.parse(data);
JSONObject jsonObject = (JSONObject) obj;
resultJson = (String) jsonObject.get("projectId");
resultJson += "\n";
resultJson += (String) jsonObject.get("userName");
but I get the error [java.lang.ClassCastException: org.json.simple.JSONArray cannot be cast to org.json.simple.JSONObject] And also I don't understand how I will get the values in lower level without a key. I tried also to save it as a JSONArray but it didn't work.
your root of json is type of JSONArray,
the first object stored in the root array is an object, you can retrieve it by using index = 0 .
this is a hack to make your code work:
JSONArray jsonArray = JSONArray.fromObject(data);
JSONObject jsonObject=obj.getJSONObject(0);
resultJson = (String) jsonObject.get("projectId");
resultJson += "\n";
resultJson += (String) jsonObject.get("userName");
NOTE:
to convert a String to JSONArray, you can do :
JSONArray array = JSONArray.fromObject(data);
To improve on nafas answer, I would do this to see all the objects in the array:
Object obj = parser.parse(data);
JSONArray jsonArray = (JSONArray) obj;
for (int i = 0; i < jsonArray.size (); i++) {
JSONObject jsonObject=obj.getJSONObject(i);
resultJson = (String) jsonObject.get("projectId");
resultJson += "\n";
resultJson += (String) jsonObject.get("userName");
}
How to parse this json? I want get data from title, field_place and brothers fields.
{
"events": [
{
"event": {
"title": "BITUMIX Martyna Jastrz\u0119bska",
"field_place": "Nowe Miejsce Al Jerozolimskie 51 lok.2",
"field_zdjecie": "http:\/\/wybierzkulture.waw.pl\/sites\/default\/files\/styles\/post\/public\/martyna_jastrzebska_bitumix_2.jpg?itok=nd2O5U5z"
}
},
{
"event": {
"title": "Wiecz\u00f3r Komedii Improwizowanej - D\u017cem Impro!",
"field_place": "",
"field_zdjecie": "http:\/\/wybierzkulture.waw.pl\/sites\/default\/files\/styles\/post\/public\/dzem_17_maja.jpg?itok=bfgDYxKq"
}
},
...
I tried:
JSONObject itemm = jArray.getJSONObject(i);
JSONObject oneObject = itemm.getJSONObject("event");
String title = oneObject.getString("title");
String field_place = oneObject.getString("field_place");
... but it doesn't work.
In a JSON string , there are two symbols that guide you through parsing :
{ - indicates a JSONObject
[ - indicates a JSONArray
When parsing a json string, you should go through this items iteratively. To understand how many JsonObjects and JsonArrays you have in your string , and from which you should start parsing, use a json-visualizer tool like this website. :
Example : As you see, the root object is a JSONObject which consists of an JSONArray with three jsonOnjects. To parse such a structure you can use :
JSONObject jsonobj = new JSONObject(jsonstring);
String result = jsonObject.getString("success");
String error_number = jsonObject.getString("error_number");
String error_message = jsonObject.getString("error_message");
JSON Array jsonarray = jsonobj.getJSONArray();
String[] names = new String[jsonArray.length()];
String[] formattedNames = new String[jsonArray.length()];
for(int i=0;i<jsonArray.length();i++)
{
JSONObject jsonObject = jsonArray.getJSONObject(i);
names [i] = jsonObject.getString("name");
formattedNames [i] = jsonObject.getString("formattedName");
}
try this
JSONArray element = jsonobj.getJSONArray("events");
for(int i=0;i < element.length();i++){
JSONObject e = element.getJSONObject(i);
Log.d("TESTTT22",e.getJSONObject("event").getString("title"));
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
How can I parse in Android a Json array of strings and save it in a java string array ( like: xy[ ] ) ?
My Json to be parsed :
[
{
"streets": [ "street1", "street2", "street3",... ],
}
]
Later in my code I want to populated with that array a spinner item in my layout.
Everything i tried enden with only one street item listed in the spinner.
To parse
try {
JSONArray jr = new JSONArray("Your json string");
JSONObject jb = (JSONObject)jr.getJSONObject(0);
JSONArray st = jb.getJSONArray("streets");
for(int i=0;i<st.length();i++)
{
String street = st.getString(i);
Log.i("..........",""+street);
// loop and add it to array or arraylist
}
}catch(Exception e)
{
e.printStackTrace();
}
Once you parse and add it to array. Use the same to populate your spinner.
[ represents json array node
{ represents json object node
Try this..
JSONArray arr = new JSONArray(json string);
for(int i = 0; i < arr.length(); i++){
JSONObject c = arr.getJSONObject(i);
JSONArray ar_in = c.getJSONArray("streets");
for(int j = 0; j < ar_in.length(); j++){
Log.v("result--", ar_in.getString(j));
}
}
We need to make JSON object first. For example,
JSONObject jsonObject = new JSONObject(resp);
// resp is your JSON string
JSONArray arr = jsonObject.getJSONArray("results");
Log.i(LOG, "arr length = " + arr.length());
for(int i=0;i<arr.length();i++)
{...
arr may contains other JSON Objects or JSON array. How to convert the JSON depends on the String. There is a complete example with some explanation about JSON String to JSON array can be found at http://www.hemelix.com/JSONHandling