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.
Related
If my request returns a JSON object like this
{"autocomplete":["abc", "asd"]}
How can I get the array in the JSON and turn it into java ArrayList?
I find some methods like getString, getInt. But I don't find a method that could get the array.
val response = JSONObject(yourresponse)
val Jarray: JSONArray = response.getJSONArray("autocomplete")
for (i in 0 until Jarray.length()) {
val jsonobject: JSONObject = jsonarray.getJSONObject(i)
Log.e("TAG",jsonobject.toString())
}
In this way you can do
String response = new JSONObject(response);
JSONArray array= c.getJSONArray("autocomplete");
for (int i = 0; i < array.length(); i++){
JSONObject a = carteVisite.getJSONObject(j);
Log.d("TAG", a);
}
Hello I am building a Spring Boot app with Thymeleaf and I am receiving from an API a JSON that I have to put in the HTML page. This is the JSON:
{"mesaje":[{"data_creare":"202205191249","cif":"1111111111118","id_solicitare":"205804","detalii":"Erori de validare identificate la factura primita cu id_incarcare=205804","tip":"ERORI FACTURA","id":"9279339"}
This is what I have tried:
String raspuns = service.getListaMesaje(zile, select);
System.out.println("------------------------"+raspuns);
JsonParser parser = new JsonParser();
JsonObject obj = parser.parse(raspuns).getAsJsonObject();
//String eroare = obj.get("eroare").getAsString();
String mesaje = obj.get("mesaje").getAsString();
JSONObject responseObject = new JSONObject(raspuns);
JSONArray jsonArray = (JSONArray) responseObject.get("mesaje");
JSONObject jsonObject = (JSONObject) jsonArray.get(0);
String dataCreare = jsonObject.getString("data_creare");
model.addAttribute("data_creare", dataCreare);
In the console the JSON prints but I get this error also in the console:
java.lang.IllegalStateException: null
Can someone show me an example how to extract the values from mesaje parent in the JSON ?
Thank you
I suggest you to use gson library for that.
Then, after you added gson dependency in pom.xml, you can extract values from your JSON string with this few lines of code :
String raspuns = "{\"mesaje\":[{\"data_creare\":\"202205191249\",\"cif\":\"1111111111118\",\"id_solicitare\":\"205804\",\"detalii\":\"Erori de validare identificate la factura primita cu id_incarcare=205804\",\"tip\":\"ERORI FACTURA\",\"id\":\"9279339\"}]}";
JsonObject jsonObject = new JsonParser().parse(raspuns).getAsJsonObject();
JsonArray arr = jsonObject.getAsJsonArray("mesaje");
for (int i = 0; i < arr.size(); i++) {
String data_creare = arr.get(i).getAsJsonObject().get("data_creare").getAsString();
String cif = arr.get(i).getAsJsonObject().get("cif").getAsString();
String id_solicitare = arr.get(i).getAsJsonObject().get("id_solicitare").getAsString();
String detalii = arr.get(i).getAsJsonObject().get("detalii").getAsString();
String tip = arr.get(i).getAsJsonObject().get("tip").getAsString();
String id = arr.get(i).getAsJsonObject().get("id").getAsString();
System.out.println(data_creare);
System.out.println(cif);
System.out.println(tip);
System.out.println(id_solicitare);
System.out.println(detalii);
System.out.println(id);
}
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");
}
Hello how to get data from Json Array in another Json array i have get data till attachments but attachment doesnt work, All code work till attachments how to get data from attachments I need to get "photo_75" from it
Json
"response":{
"count":3,
"items":[
{
"id":3,
"from_id":205110032,
"owner_id":-81865402,
"date":1417672154,
"post_type":"post",
"text":"jjjjASDFGHJKYTRDXCVB",
"attachments":[
{
"type":"photo",
"photo":{
"id":330414711,
"album_id":-7,
"owner_id":205110032,
"photo_75":"http:\/\/cs605116.vk.me\/v605116032\/6325\/3SwTo8j4lJ0.jpg",
"photo_130":"http:\/\/cs605116.vk.me\/v605116032\/6326\/_OZA86FO3Nw.jpg",
"photo_604":"http:\/\/cs605116.vk.me\/v605116032\/6327\/AUtB59708Nw.jpg",
"photo_807":"http:\/\/cs605116.vk.me\/v605116032\/6328\/59oAdfz9jgI.jpg",
"width":538,
"height":807,
"text":"",
"date":1399134687,
"access_key":"7297eb663de2e4e6b2"
}
}
],
"comments":{
"count":0
},
"likes":{
"count":0
},
"reposts":{
"count":0
}
},
Java
private void parseJsonFeed(JSONObject response) {
try {
JSONObject parent = response.getJSONObject("response");
JSONArray feedArray = parent.getJSONArray("items");
for (int i = 0; i < feedArray.length(); i++) {
JSONObject feedObj = (JSONObject) feedArray.get(i);
FeedItem item = new FeedItem();
item.setId(feedObj.getInt("id"));
item.setName(feedObj.getString("post_type"));
item.setTimeStamp(feedObj.getString("date"));
// Image might be null sometimes
String image = feedObj.isNull("photo") ? null : feedObj
.getString("photo");
item.setImge(image);
item.setStatus(feedObj.getString("text"));
All code work till there how to get data from attachments
***JSONObject response1 = response.getJSONObject("response");
feedArray = parent.getJSONArray("items");***
JSONArray feedArray1 = response1.getJSONArray("attachments");
for (int i1 = 0; i1 < feedArray1.length(); i1++) {
JSONObject feedObj1 = (JSONObject) feedArray1.get(i1);
FeedItem item1 = new FeedItem();
item.setProfilePic(feedObj1.getString("photo_75"));
}
// url might be null sometimes
String feedUrl = feedObj.isNull("url") ? null : feedObj
.getString("url");
item.setUrl(feedUrl);
feedItems.add(item);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
Thanks in advance
you are looking for attachments in wrong object. "attachmetnts" is property of item.
instead of
JSONArray feedArray1 = response1.getJSONArray("attachments");
use
JSONArray feedArray1 = feedObj.getJSONArray("attachments");
in your case feedObj contains item object.
to get photo :
Remove lines :
String image = feedObj.isNull("photo") ? null : feedObj
.getString("photo");
item.setImge(image);
and change it to :
for (int i1 = 0; i1 < feedArray1.length(); i1++) {
JSONObject attachment = (JSONObject) feedArray1.get(i1);
JSONObject photo = (JSONObject) attachment.getJSONObject("photo");
item.setImge(photo);
item.setProfilePic(photo.getString("photo_75"));
item.setStatus(photo.getString("text"));
}
You can try GSON, which would directly give you a java object from your json and you would not have to parse it manually.
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();
}