you need to make a JSON Array first and then store that
private String mUrl;
private ArrayList<String> mUrlDove;
HashMap<String, String> params = new HashMap<String, String>();
params.put("url", mUrl);
JSONArray jsArray = new JSONArray(mUrlDove);
params.put("urlDove", jsArray.toString());
mUrl = app.getInstance().getmUrlRestWS() + getString(R.string.path);
JsonObjectRequest mRequest = new JsonObjectRequest(
mUrl, new JSONObject(params),
createMyReqSuccessListener(),
createMyReqErrorListener()) {
@Override
public Map<String, String> getHeaders() throws AuthFailureError {
return app.getInstance().createBasicAuthHeader();
}
};
Answer from Tomer Shemesh on Stack Overflowyou need to make a JSON Array first and then store that
private String mUrl;
private ArrayList<String> mUrlDove;
HashMap<String, String> params = new HashMap<String, String>();
params.put("url", mUrl);
JSONArray jsArray = new JSONArray(mUrlDove);
params.put("urlDove", jsArray.toString());
mUrl = app.getInstance().getmUrlRestWS() + getString(R.string.path);
JsonObjectRequest mRequest = new JsonObjectRequest(
mUrl, new JSONObject(params),
createMyReqSuccessListener(),
createMyReqErrorListener()) {
@Override
public Map<String, String> getHeaders() throws AuthFailureError {
return app.getInstance().createBasicAuthHeader();
}
};
try passing JSONObject instead of hashmap
JSONObject params = new JSONObject();
params.put("url", "www.secret.com");
JSONArray urlDove = new JSONArray();
urlDove.put("www.google.com");
urlDove.put("www.yahoo.com");
params.put("urlDove", urlDove);
JsonObjectRequest mRequest = new JsonObjectRequest(
mUrl, params,
createMyReqSuccessListener(),
createMyReqErrorListener()) {
@Override
public Map<String, String> getHeaders() throws AuthFailureError {
return app.getInstance().createBasicAuthHeader();
}
};
for reference in parsing json https://stackoverflow.com/a/17810270/4810752
java - Creating an ArrayList from a JSON Object - Stack Overflow
java - How to add ArrayList<String> to JSON Array - keeping type safety in mind - Stack Overflow
java - How to convert ArrayList to JSON object - Stack Overflow
Json object to java arraylist - Stack Overflow
public class Semester {
private static final String JSON_ID = "id";
private static final String JSON_TITLE = "title";
private static final String JSON_CREDITS = "credits";
private static final String JSON_GPA = "gpa";
private static final String JSON_CUMULATIVECREDITS = "cumulativecredits";
private static final String JSON_CUMULATIVEGPA = "cumulativegpa";
private static final String JSON_COURSES = "courses";
private UUID id;
private String title;
private int credits;
private double GPA;
private int cumulativeCredits;
private double cumulativeGPA;private ArrayList<Course> courses;
public Semester() {
id = UUID.randomUUID();
courses = new ArrayList<Course>();
for (int i = 0; i < 6; i++) {
courses.add(new Course());
}
}
public Semester(JSONObject json) throws JSONException {
id = UUID.fromString(json.getString(JSON_ID));
title = json.getString(JSON_TITLE);
credits = json.getInt(JSON_CREDITS);
GPA = json.getDouble(JSON_GPA);
cumulativeCredits = json.getInt(JSON_CUMULATIVECREDITS);
cumulativeGPA = json.getDouble(JSON_CUMULATIVEGPA);//what do i put here?
}
public JSONObject toJSON() throws JSONException {
JSONObject json = new JSONObject();
json.put(JSON_ID, id.toString());
json.put(JSON_TITLE, title);
json.put(JSON_CREDITS, credits);
json.put(JSON_GPA, GPA);
json.put(JSON_CUMULATIVECREDITS, cumulativeCredits);
json.put(JSON_CUMULATIVEGPA, cumulativeGPA);JSONArray array = new JSONArray(courses);
json.put(JSON_COURSES, array);
return json; } .........
This is followed by a bunch of getters and setters for each private variable.
The first bolded item is the private ArrayList of a custom class that I made.
The second bolded item is what I need help with: how to retrieve the custom ArrayList just like the other variables.
Lastly, the third bolded item is my current idea of how to put an ArrayList into a JSONObject, but I don't know how to retrieve it. If there is another way, please tell me. Thank you.
If you want to work with json go this library, this library has a nice support https://code.google.com/p/google-gson/.
This is an example:
Gson gson = new Gson();
Collection<Integer> ints = Lists.immutableList(1,2,3,4,5);
(Serialization)
String json = gson.toJson(ints); ==> json is [1,2,3,4,5]
Thanks
org.json and org.json.simple JSON parser use raw types of collections underneath. If you're looking for good Generics support try Google Gson. Here's how you would go about serializing your generic ArrayList with Gson:
Gson gson = new Gson();
ArrayList<String> arrayList= (ArrayList<String>) ClassName.getArrayList();
// Serializing to a JSON element node
JsonElement jsonElement = gson.toJsonTree(arrayList);
System.out.println(jsonElement.isJsonArray()); // true
// Or, directly to JSON string
String json = gson.toJson(arrayList);
System.out.println(json);
Here's how you would deserialize the same JSON string with its Generics intact:
Type type = new TypeToken<ArrayList<String>>(){}.getType();
ArrayList<String> arrayList = gson.fromJson(json, type);
You can use the GSON library to accomplish this.
ArrayList<String> mylist = new ArrayList<String> ();
mylist.add("abc");
mylist.add("cfd");
mylist.add("ert");
mylist.add("fg");
mylist.add("ujk");
String json = new Gson().toJson(mylist);
You can refer to the GSON User Guide for more support.
JSONArray jsArray = new JSONArray(mylist);
Or
Gson gson = new Gson();
String jsonArray = gson.toJson(mylist);
Get java-json.jar and Gson.jar here
Create instance of JsonArray then add json element to that array using key.
Here is your solution :
Gson googleJson = new Gson();
JsonObject data = googleJson.fromJson(request.getReader(), JsonObject.class);
System.out.println(data);
JsonArray jsonArr = new JsonArray();
for(Entry<String, JsonElement> entry : data.entrySet()) {
jsonArr.add(data.get(entry.getKey()));
}
ArrayList jsonObjList = googleJson.fromJson(jsonArr, ArrayList.class);
for(int i = 0; i < jsonObjList.size(); i++) {
System.out.println(jsonObjList.get(i));
}
For a Json to be a valid JsonArray object you should have it to a proper format. Can you change your json string return from your ajax? If yes you should change it to something like this:
Gson googleJson = new Gson();
JsonObject data = googleJson.fromJson("{test: [{\"0\":\"31/01/2017\"},{\"1\":\"19/01/2017\"}]}", JsonObject.class);
System.out.println(data);
JsonArray jsonArr = data.getAsJsonArray("test");
ArrayList jsonObjList = googleJson.fromJson(jsonArr, ArrayList.class);
for(int i=0; i< jsonObjList.size(); i++) {
System.out.println(jsonObjList.get(i));
}
If not you should parse it by your self and convert it to everything you want.
I think it is a problem(aka. bug) with the API you are using. JSONArray implements Collection (the json.org implementation from which this API is derived does not have JSONArray implement Collection). And JSONObject has an overloaded put() method which takes a Collection and wraps it in a JSONArray (thus causing the problem). I think you need to force the other JSONObject.put() method to be used:
jsonObject.put("aoColumnDefs",(Object)arr);
You should file a bug with the vendor, pretty sure their JSONObject.put(String,Collection) method is broken.
here is simple code
List <String> list = new ArrayList <String>();
list.add("a");
list.add("b");
JSONArray array = new JSONArray();
for (int i = 0; i < list.size(); i++) {
array.put(list.get(i));
}
JSONObject obj = new JSONObject();
try {
obj.put("result", array);
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
pw.write(obj.toString());
You can use the putArray method which creates an ArrayNode. Then you should fill it with the elements from your list.
ArrayNode arrayNode = row.putArray("myList");
for (String item : list) {
arrayNode.add(item);
}
Here is a functional way of creating an arrayNode and populate it elements from a stream. It does the same as above fracz answer :
yourStringList.stream()
.collect(Collector.of(
() -> row.putArray("myList"),
(arrayNode, item) -> arrayNode.add(item),
(arrayNode1, arrayNode2) -> { arrayNode1.addAll(arrayNode2); return arrayNode1; },
Collector.Characteristics.IDENTITY_FINISH
));
Essentially, it defines a custom collector to accumulate the elements provided by the stream. Some explanations:
- the first argument
() -> row.putArray("myList")defines the function which will provide the object to accumulate the items (called the supplier function). In our case this function will provide theArrayNodeand is the equivalent ofArrayNode arrayNode = row.putArray("myList");statement in the above answer. - the second argument
(arrayNode, item) -> arrayNode.add(item)defines the accumulator function whose role is to add the elements. In the left side of the->operator, the first variable (e.g.arrayNode) refers to the container defined in the first argument while the second (e.g.item) refers to the element to accumulate provided by the stream. This function does the same job as the statementarrayNode.add(item);inside the loop in the above example. - the third argument
(arrayNode1, arrayNode2) -> { arrayNode1.addAll(arrayNode2); return arrayNode1; }is the combiner function which is used if the stream is collected in parralel (for instance if we had.parralelStream()instead of.stream()). Its role is to merge two accumulators toghether and this is why the function has two argumets of the same type. We define this function such that it will add all elements accumulated in the second accumulator into the first accumulator and return this first accumulator. - the fourth argument
Collector.Characteristics.IDENTITY_FINISHdefine one or more optons to the process. In this case,IDENTITY_FINISHsimply states that no finisher function will be provided (to further process the accumulator object) or, in other words, that the finisher function is the identity function (no treatment done).
This solution might seems more complex at first but it leverages all the power of functionnal programming. For instance, we could stream objects, extract a String property with the map function, filter it, etc. before collecting everything:
yourObjectList.stream()
.map(o -> o.getTheStringProperty())
.filter(o -> o.length() > MIN_SIZE)
.collect(Collector.of(
() -> row.putArray("myList"),
(arrayNode, item) -> arrayNode.add(item),
(arrayNode1, arrayNode2) -> { arrayNode1.addAll(arrayNode2); return arrayNode1; },
Collector.Characteristics.IDENTITY_FINISH
));
How you iterate and add
for(int i=0;i<jsonArray.length;i++)
{
JSONObject json_data = jArray.getJSONObject(i);
imgnfo.id = json_data.getInt("id_key");
imgnfo.name = json_data.getString("name_key");
imgnfo.thumb = json_data.getString("thumb_key");
imgnfo.info = json_data.getString("info_key");
myArray.add(new image_data());
}
Just add proper keys names. I didn't know them.
Yo should post what the json data looks like. Assuming the json data looks something like
...,{
"image_data": {
"name": "image name","thumb":"thumbpath","path":"path"}
},{
"image_data": {
"name": "image name 2","thumb":"thumbpath 2","path":"path 2"}
}
Then you would extract the values like so:
ArrayList<image_data> imageArray = new ArrayList<image_data>();
for (int i=0; i<jsonArray.length(); i++) {
image_data img = new image_data();
Object jo = jsonArray.get(i);
image_data.name = jo.name;
image_data.thumb = jo.thumb;
image_data.path = jo.path;
imageArray.add(new image_data());
}
Consider using getters for you image_data class. Also consider renaming it to ImageData
Call getJSONObject() instead of getString(). That will give you a handle on the JSON object in the array and then you can get the property off of the object from there.
For example, to get the property "value" from a List<SomeClass> where SomeClass has a String getValue() and setValue(String value):
JSONObject obj = new JSONObject();
List<SomeClass> sList = new ArrayList<SomeClass>();
SomeClass obj1 = new SomeClass();
obj1.setValue("val1");
sList.add(obj1);
SomeClass obj2 = new SomeClass();
obj2.setValue("val2");
sList.add(obj2);
obj.put("list", sList);
JSONArray jArray = obj.getJSONArray("list");
for(int ii=0; ii < jArray.length(); ii++)
System.out.println(jArray.getJSONObject(ii).getString("value"));
Let us assume that the class is Data with two objects name and dob which are both strings.
Initially, check if the list is empty. Then, add the objects from the list to a JSONArray
JSONArray allDataArray = new JSONArray();
List<Data> sList = new ArrayList<String>();
//if List not empty
if (!(sList.size() ==0)) {
//Loop index size()
for(int index = 0; index < sList.size(); index++) {
JSONObject eachData = new JSONObject();
try {
eachData.put("name", sList.get(index).getName());
eachData.put("dob", sList.get(index).getDob());
} catch (JSONException e) {
e.printStackTrace();
}
allDataArray.put(eachData);
}
} else {
//Do something when sList is empty
}
Finally, add the JSONArray to a JSONObject.
JSONObject root = new JSONObject();
try {
root.put("data", allDataArray);
} catch (JSONException e) {
e.printStackTrace();
}
You can further get this data as a String too.
String jsonString = root.toString();
You coud use Gson library, that handles lists properly, instead.
Usage example:
class BagOfPrimitives {
private int value1;
private String value2;
private transient int value3;
public BagOfPrimitives(int value1, String value2, int value3) {
this.value1 = value1;
this.value2 = value2;
this.value3 = value3;
}
}
BagOfPrimitives obj1 = new BagOfPrimitives(1, "abc", 3);
BagOfPrimitives obj2 = new BagOfPrimitives(32, "gawk", 500);
List<BagOfPrimitives> list = Arrays.asList(obj1, obj2);
Gson gson = new Gson();
String json = gson.toJson(list);
// Now json is [{"value1":1,"value2":"abc"},{"value1":32,"value2":"gawk"}]
You could override the toString method in your Site class to return new JSONObject(this).toString
To convert ArrayList to Json, just download Open Source json utility from: http://json.org/java/ or Jar file from here
And just do:
JSONArray jsonAraay = new JSONArray(your_array_list);
That's it
Note: You should have setter/getter in your POJO/MODEL class to convert arraylist to json
Don't bother with org.json, use Jackson all the way:
// list is a List<MyData>
final ObjectMapper mapper = new ObjectMapper();
final Map<String, MyData> map = new HashMap<>();
for (final MyData data: list)
map.put(data.fname, data);
final JsonNode json = mapper.valueToTree(map);