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

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

Related

JSON Object cannot be converted to JSON Array [duplicate]

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

Finding Entries in JSON objects [duplicate]

This question already has answers here:
How to parse JSON in Java
(36 answers)
Closed 6 years ago.
I've got this JSON in JSON object like this
JSONObject obj = new JSONObject(json);
I now want to get back "TRUE" (control F to find where that is)
{"version":"1.0","encoding":"UTF-8","feed":{"xmlns":"Lorum","xmlns$openSearch":"Ipsum","xmlns$gsx":"Dolor","id":{"$t":"Lorum"},"updated":{"$t":"2016-07-30T07:40:03.369Z"},"category":[{"scheme":"Ipsum","term":"Dolar"}],"title":{"type":"text","$t":"Sheet1"},"link":[{"rel":"alternate","type":"application/atom+xml","href":"Lorum"},{"rel":"Ipsum","type":"application/atom+xml","href":"Dolor"},{"rel":"Lorum","type":"application/atom+xml","href":"Ipsum"},{"rel":"self","type":"application/atom+xml","href":"Dolor"}],"author":[{"name":{"$t":"spark"},"email":{"$t":"Lorum"}}],"openSearch$totalResults":{"$t":"1"},"openSearch$startIndex":{"$t":"1"},"entry":[{"id":{"$t":"Ipsum"},"updated":{"$t":"2016-07-30T07:40:03.369Z"},"category":[{"scheme":"Dolor","term":"Lorum"}],"title":{"type":"text","$t":"Ipsum"},"content":{"type":"text","$t":"parko2: TRUE"},"link":[{"rel":"self","type":"application/atom+xml","href":"Lorum"}],"gsx$parko1":{"$t":"TRUE"},"gsx$parko2":{"$t":"FALSE"},"gsx$indexfilteraanotisblankaarowsfilteraanotisblankaa":{"$t":""}}]}}
JSONObject obj = new JSONObject(json);
JSONObject obj1 =obj.getJsonObject("feed");
JsonArray array = obj1.getJsonArray("entry");
You will get array of entry array

Convert returned JSON String to a JSONArray

I have a web service that performs a database query, converts the result set to a JSON String and returns the strung to the client. This is the code for the converter (I got it from http://biercoff.com/nice-and-simple-converter-of-java-resultset-into-jsonarray-or-xml/):
public static String convertToJSON(ResultSet resultSet)
throws Exception {
JSONArray jsonArray = new JSONArray();
while (resultSet.next()) {
int total_rows = resultSet.getMetaData().getColumnCount();
JSONObject obj = new JSONObject();
for (int i = 0; i < total_rows; i++) {
obj.put(resultSet.getMetaData().getColumnLabel(i + 1)
.toLowerCase(), resultSet.getObject(i + 1));
}
jsonArray.add(obj);
}
return jsonArray.toJSONString();
}
In the client application when I print the returned string it is in the following format:
[{"Column1":0.333333,"Column2":"FirmA"},{"Column1":0.666667,"Column2":"FirmB"}]
so far all is good. The problem I am having is converting the returned string into a JSON array. I tried this:
JSONArray arr = new JSONArray(JSON_STRING);
but got the following error message: constructor JSONArray in class JSONArray cannot be applied to given types. I tried to first convert in into a JSON object like so:
JSONObject obj = new JSONObject(JSON_STRING);
but got the following error: incompatible types: String cannot be converted to Map. What am I doing wrong? Thanks.
Apparently the problem was with the json library that I was using. Once I used the
import org.json.JSONArray;
it all worked out well. I was able to convert the returned string to an array using
JSONArray arr = new JSONArray(JSON_STRING);
and to iterate through the values I used the code provided in this answer: Accessing members of items in a JSONArray with Java which I reproduce here for simplicity:
for (int i = 0; i < arr.length(); ++i) {
JSONObject rec = arr.getJSONObject(i);
int id = rec.getInt("id");
String loc = rec.getString("loc");
// ...
}
well you need to do it by this way for example
String jsonText = "[0,{\"1\":{\"2\":{\"3\":{\"4\":[5,{\"6\":7}]}}}}]";
try {
JSONArray array = new JSONArray(jsonText);
System.out.println(array);
System.out.println(array.length());
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
}
Check the correct library used. The mess is that org.json.simple is often suggested by IDE as default for JSONObject and JSONArray.
You can find a link to latest jar for org.json library above.

how to read JSON from HTTP GET request?

I have created a java server which gets HTTP GET request url as
/Star/getDetails?sentMsg=data.requestorName:ABC,data.companyName:EFG,portfolios:
[{name:,placeholder:Portfolio 1,positions:[{ticker:T1234,weight:29.85},
{ticker:T2345,weight:70.15}],active:false}],analyticsDate:20140630}
I have to parse sentMsg parameter such as I am able to read each variable individually. For eg, i should be able to read data.requestorName, companyName. I am not able to find a way to do it.
request.getParameter("sentMsg") always return String.
Tried parsing it through json-simple
JSONParser jp = new JSONParser();
try {
Object obj = jp.parse(sentMsg);
JSONArray ja = (JSONArray)obj;
} catch (ParseException e) {
e.printStackTrace();
}
But this gives parse exception. I have limitation to use json-simple jar only. Any suggestion on how to do it?
Get the paramter sentMsg from HttpRequest object store it into a string. Split from comma i.e. "," and the last second token would be the json string. You can now parse it using Json simple lib and extract values from it.
Provided you have valid JSON like:
private static String jsonString = "[{name : \"stackOverFlow\"}]";
Convert it to JSONArray like:
JSONArray jsonArray = new JSONArray(jsonString );
Then you can get value out of JSONArray by looping through it:
for (int i = 0; i < jsonArray.length(); i++) { //Iterating over mediaArray
JSONObject media = jsonArray.getJSONObject(i);
String nameFromJSON = media.getString("name");
System.out.println("Name = " + nameFromJSON);
}
Output will be:
//Name = stackOverFlow

how do i add String array to JSON

I am currently writing some code in a servlet that gets data from the database and returns it to the client. What I am having problems with is inserting the array of dates I have collected and adding them to my JSON object that I will return to the client.
Here is the code I'm trying but it keeps giving errors
dates = ClassdatesDAO.getdate(dates);
ArrayList<String> ClassDates = new ArrayList<String>();
ClassDates = dates.getClassdates();
response.setContentType("application/json");
JSONObject Dates = new JSONObject();
Dates.put("dates", new JSONArray(ClassDates));
In my IDE I get this error over the ClassDates in the JSONArray
The constructor JSONArray(ArrayList) is undefined
You are passing ArrayList instance instead of an Array. So, convert the list into an array and then pass it as an argument like this
Dates.put("dates", new JSONArray(ClassDates.toArray(new String[ClassDates.size()])));
Note : json API has a method signature accepting java.util.Collection. So, you are using some other library or older version
JSONObject Dates = new JSONObject();
JSONArray datesJSONArray = new JSONArray();
for (String date : ClassDates)
datesJSONArray.put(date);
try {
Dates.put("dates", datesJSONArray);
} catch (JSONException e) {
e.printStackTrace();
}

Categories