JSON Object cannot be converted to JSON Array [duplicate] - java

This question already has answers here:
org.json.JSONObject cannot be converted to JSONArray in android
(6 answers)
Closed 5 years ago.
I am getting this error when I am trying to convert following JSON response string from the server. I want to process JSONObject or JSONArray depending on the response from the server as most of the time it returns JSONArray.
JSON response from server
jsonString = {"message":"No Results found!","status":"false"}
Java code is as below
try
{
JSONArray jsonArrayResponse = new JSONArray(jsonString);
if(android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.KITKAT)
{
if(jsonArrayResponse != null && jsonArrayResponse.length() > 0)
{
getCancelPurchase(jsonArrayResponse.toString());
}
}
}
catch(JSONException e)
{
e.printStackTrace();
}
Error Log:
org.json.JSONException: Value {"message":"No Results found!","status":"false"} of type org.json.JSONObject cannot be converted to JSONArray
at org.json.JSON.typeMismatch(JSON.java:111)
at org.json.JSONArray.<init>(JSONArray.java:96)
at org.json.JSONArray.<init>(JSONArray.java:108)
Can anybody help me.
Thanks

Based on your comment to answer 1, you can do is
String data = "{ ... }";
Object json = new JSONTokener(data).nextValue();
if (json instanceof JSONObject)
//you have an object
else if (json instanceof JSONArray)
//you have an array

Your response {"message":"No Results found!","status":"false"} is not an array. It is an object. Use JSONObject instead of JSONArray in your code.
TIP: Arrays are wrapped in square brackets[ ] and objects are wrapped in curly braces{}.

I fix this issue by writing following code [ courtesy #Optional ]
String jsonString = "{\"message\":\"No Results found!\",\"status\":\"false\"}";
/* String jsonString = "[{\"prodictId\":\"P00001\",\"productName\":\"iPhone 6\"},"
+ "{\"prodictId\":\"P00002\",\"productName\":\"iPhone 6 Plus\"},"
+ "{\"prodictId\":\"P00003\",\"productName\":\"iPhone 7\"}]";
*/
JSONArray jsonArrayResponse;
JSONObject jsonObject;
try {
Object json = new JSONTokener(jsonString).nextValue();
if (json instanceof JSONObject) {
jsonObject = new JSONObject(jsonString);
if (jsonObject != null) {
System.out.println(jsonObject.toString());
}
} else if (json instanceof JSONArray) {
jsonArrayResponse = new JSONArray(jsonString);
if (jsonArrayResponse != null && jsonArrayResponse.length() > 0) {
System.out.println(jsonArrayResponse.toString());
}
}
} catch (JSONException e) {
e.printStackTrace();
}

Related

Parse JSON having both Escape & Unescape characters in JAVA using Jayway

I receive the below json as an input to my program:
{
"shopping": {
"cart": {
"items": [{
"iturl" : "https://www.google.com/",
"itdesc" : "Item’s box includes the below contents:\n a.adaptor \n b.sdfd"
}]
}
}
}
We are using jayway jsonpath to parse this data and do some processing and return the final value as a string.
when we parse it with the default jsonpath configuration, I get the iturl modified as "https:\/\/www.google.com\/"
Tried changing the JSONProvider to JacksonJsonProvider (by referring Jsonpath with Jackson or Gson) and the issue with the url is solved but, the value of itdesc is now coming to new line (due to \n) making it an invalid json.
I cannot specifically handle for each field as the incoming data will be dynamic.
Is there any proper way to parse this kind of JSON in java. Thanks in advance for your help
Try adding one more escaping level before parsing the string, the string parser's gonna give you "\n" for "\\n".
For example, parsing with Jackson ObjectMapper.
objectMapper.readValue(jsonString.replace("\\", "\\\\"), Any.class);
{
"shopping": { <-- JSONObject
"cart": { <-- JSONObject
"items": [{ <-- JSONArray
"iturl" : "https://www.google.com/", <-- JSONObject inside JSONAray
"itdesc" : "Item’s box includes the below contents:\n a.adaptor \n b.sdfd"
}]
}
}
}
if this data json come from http connection.
this json must be a string format fisrt,
and try using org.json.simple
so do like this :
private void readData() {
String Body = (response json string from connection);
JSONParser parse = new JSONParser();
String iturl = null;
String itdesc = null;
try {
JSONObject shopping = (JSONObject) parse.parse(Body);
JSONObject cart= (JSONObject) shopping.get("cart");
JSONArray items = (JSONArray ) cart.get("items ");
items.forEach((k)-> {
JSONObject inside = (JSONObject) k;
iturl = inside.get("iturl");
itdesc = inside.get("itdesc");
});
}catch ( ParseException e) {
e.printStackTrace();
}
}
if this come from file.json combine with reader :
private static final File jsonData = new File(file.json);
private void callData() {
String iturl = null;
String itdesc = null;
try {
Reader reader = new FileReader(marketList);
JSONParser parse = new JSONParser();
JSONObject shopping = (JSONObject) parse.parse(reader);
JSONObject cart= (JSONObject) shopping.get("cart");
JSONArray items = (JSONArray ) cart.get("items ");
items.forEach((k)-> {
JSONObject inside = (JSONObject) k;
iturl = inside.get("iturl");
itdesc = inside.get("itdesc");
});
} catch (IOException | ParseException e) {
e.printStackTrace();
}
}

string in correct json format but im still getting error while converting

im trying to convert data from json array to json object but I'm getting an error and I don't know why
java code here
void addToList(String json)
{
try
{
ja = new JSONArray(json);
for(int i = 0;i<ja.length();i++)
{
JSONObject item = ja.getJSONObject(i);
String sent = item.getString("#")+" x "+item.getString("name");
items.add(sent);
}
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1,items);
itemlist.setAdapter(adapter);
}
catch (JSONException e)
{
e.printStackTrace();
}
}
json = ["{"name":"fish","#":"1"}"]
and the error I'm getting is
org.json.JSONException: Value {"name":"fish","#":"1"} at 0 of type java.lang.String cannot be converted to JSONObject
This is the constructor of a JSONObject:
Parameters:
source - `A string beginning with { (left brace) and ending with } (right brace).`
Throws:
JSONException - If there is a syntax error in the source string or a duplicated key.
That means in your case specifically that json can't be an array. Try using something like:
json = "{"name":"fish","#":"1"}"

How to convert a jsonArray into List<String> Java? [duplicate]

This question already has answers here:
Convert Json Array to normal Java list
(16 answers)
Closed 3 years ago.
I am using openjdk 11 and I am calling an api that is returning content type json. I parsing the response and converting into a string like this ( Need to do it this way as I am expecting responses in different formats/structure):
HttpEntity entity = response.getEntity();
try
{
responseBody = EntityUtils.toString( entity );
}
catch ( Exception e )
{
LOG.error( "Unable to parse response", e );
e.printStackTrace();
}
Where response is a org.apache.http.HttpResponse type object.
After converting into a string, the response looks like :
["abc","bcd","cde"]
Now, I was trying to put this into jsonObject or JsonArray as
JSONArray jsonArray = new JSONArray(responseBody);
Arrays.asList(jsonArray).stream().forEach(e-> LOG.info("Connector: " + e));
While my jsonArray looks good, getting error like :
["abc","bcd","cde"] is not an array
Question is : How to convert that jsonArray into a List in Java ?
I assume JSONArray comes from Android. You can just do this:
ArrayList<String> list = new ArrayList<String>();
JSONArray jsonArray = (JSONArray)jsonObject;
if (jsonArray != null) {
int len = jsonArray.length();
for (int i=0;i<len;i++){
list.add(jsonArray.get(i).toString());
}
}
Source: Convert Json Array to normal Java list

How to parse json response, when the response does not contain header information

I am trying to parse a json response so that i can get elements out of an object, getting the following error A JSONObject text must begin with '{' at 1 [character 2 line 1]
public static String parseJsonResponse(String json){
String uId ="";
try {
JSONObject jsonObj = new JSONObject(json);
// String fname = jsonObj.getString("fname");
//String lname = jsonObj.getString("lname");
String aId = jsonObj.getString("id");
uId = aId;
} catch (Exception e) {
e.printStackTrace();
}
return uId;
}
Here is json response using postman you will notice there is no header
[
{
"id": "emplo000000000043567",
"displayName": "Tester, user1",
},
{
"id": "emplo000000000035386",
"displayName": "Tester, User2",
}
]
Like the comment above mentioned, that is a JSON array so it needs to be parsed as a JSON array and not a JSON object. Just use the JSONArray equivalent provided in the library you are using.
On another note, with the JSON response above, parsing this as a JSON array would fail since the format is incorrect. Notice the comma at the end of every last keyvalue in each object. That would cause the parser to fail when attempting to parse that as a JSON array. If that was your mistake when you were writing the snippet here then ignore this paragraph. Else if that was the actual JSON response then I guess you need to make a new question... over at the Postman forum.
There are several ideas for this case.
Here is mine.
With a json simple library[link].
You can simply change your library to a json simple library which has a parser class for a json string
then use an instanceof method for detection before processing a json object.
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
public static String parseJsonResponse(String json){
String uId ="";
try {
JSONParser parser = new JSONParser();
Object whichone = parser.parse(json);
if(whichone instanceof JSONObject)
{
JSONObject jsonObj = (JSONObject)whichone;
// String fname = jsonObj.getString("fname");
//String lname = jsonObj.getString("lname");
if(jsonObj.containsKey("id"))
uId = (String)jsonObj.get("id");
}
else if(whichone instanceof JSONArray)
{
JSONArray jsonArr = (JSONArray)whichone;
JSONObject jsonObj = null;
for(int i = 0; i < jsonArr.size(); i++)
{
jsonObj = (JSONObject) jsonArr.get(i);
if(jsonObj.containsKey("id"))
{
uId = (String)jsonObj.get("id");
System.out.println(uId);
}
}
}
else if(whichone instanceof String)
{
System.out.println("1?????" + whichone.toString());
}
else
{
System.out.println("2?????" + whichone.toString());
}
} catch (Exception e) {
e.printStackTrace();
}
return uId;
}
Detect the object type from a json excetpion.
You can catch it whether some string is a json object or json array during exception handling.
import org.json.JSONArray;
import org.json.JSONObject;
public static String parseJsonResponse(String json){
String uId ="";
try {
JSONObject jobj = new JSONObject(json);
if(jobj.has("id"))
uId = jobj.getString("id");
System.out.println(uId);
} catch (org.json.JSONException e) {
//e.printStackTrace();
JSONArray jsonArr = new JSONArray(json);
JSONObject jsonObj = null;
for(int i = 0; i < jsonArr.length(); i++)
{
jsonObj = jsonArr.getJSONObject(i);
if(jsonObj.has("id"))
{
uId = (String)jsonObj.get("id");
System.out.println(uId);
}
}
}
return uId;
}
With a java work.
You can find it whether it's a json object or array after parsing a first character.
(I think it will work...)
import org.json.JSONArray;
import org.json.JSONObject;
public static String parseJsonResponse(String json){
String uId ="";
boolean isJobj = json.charAt(0) == '[';
if(!isJobj) {
JSONObject jobj = new JSONObject(json);
if(jobj.has("id"))
uId = jobj.getString("id");
System.out.println(uId);
} else {
JSONArray jsonArr = new JSONArray(json);
JSONObject jsonObj = null;
for(int i = 0; i < jsonArr.length(); i++)
{
jsonObj = jsonArr.getJSONObject(i);
if(jsonObj.has("id"))
{
uId = (String)jsonObj.get("id");
System.out.println(uId);
}
}
}
return uId;
}
Have a good day..
First, Your json format is wrong. The correct json format would be:
[
{
"id": "emplo000000000043567",
"displayName": "Tester, user1"
},
{
"id": "emplo000000000035386",
"displayName": "Tester, User2"
}
]
Now,
Your Response is JSON Array. So first assign parsed object into JSON Array as JSONArray array = (JSONArray) obj;
this JSON Array consists of two JSON Object so traverse the array, get each JSON Object and print/return key/value pair whatever you want.
A sample code is given below:(see the logic)
public static void parseJsonResponse(String json)
throws JsonParseException, JsonMappingException, IOException, ParseException {
String aId ="";
JSONParser parser = new JSONParser();
Object obj = parser.parse(json);
JSONArray array = (JSONArray) obj;
for(int i=0;i<array.size();i++)
{
JSONObject jsonObject = (JSONObject) array.get(i);
aId = (String) jsonObject.get("id");
System.out.println(aId);
}
}
Note: I have used json-simple java library here.

How to Read Json array values from file

JSONArray jsonArray = (JSONArray) obj;
When I use the above code, it shows the error message:
java.lang.ClassCastException: org.json.simple.JSONObject cannot be cast to org.json.simple.JSONArray
Please anyone suggest any method to overcome this error or any other way to read json value form a file in Java (Desktop application).
Use this for get json value in string format from file
public String loadJSONFromFile() {
String json = null;
try {
InputStream is = getActivity().getAssets().open("yourfilename.json");
int size = is.available();
byte[] buffer = new byte[size];
is.read(buffer);
is.close();
json = new String(buffer, "UTF-8");
} catch (IOException ex) {
ex.printStackTrace();
return null;
}
return json;
}
JsonObject is a child of a JsonArray, so as per my suggestion use like this
final JSONArray jsonArray = new JSONArray();
jsonArray.put(obj); //obj is your JsonObject
and you can get JsonObject from array like
jsonArray.getJSONObject(0); //0 is index of your JsonObject in JsonArray
Hope this help you.
Check the content of the file.
It seems that the content is not an array, but a json object.
Open the file with a text editor. If the content is something like:
{ // First character
... content here
} // Last character
it is an object, if it is similar to
[ // First character
... content here
] // Last character
it is an array.
If you need to read an object you need to change your code as follow:
JSONObject jsonObject = (JSONObject) obj;
JSONArray jsonArray = (JSONArray) obj;
This obj is of JsonObject type, so change that line to
JSONObject jsonObject = (JSONObject)obj;

Categories