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"));
Answer from Rob Tanzola on Stack OverflowCall 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();
java - Adding JSON data to arrayList - Stack Overflow
java - How to write a json to add a list? - Stack Overflow
How to convert JSON string into List of Java object? - Stack Overflow
java - Adding a List to Json ObjectNode - Stack Overflow
Videos
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.
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
JSONObject final = new JSONObject();
JSONArray ja = new JSONArray();
try {
Statement ac = DBL.getConnection().createStatement();
ResultSet r5 = ac.executeQuery("Select * from msg");
while(r5.next()){
System.out.println("Value taken from database"+r5.getString("content"));
JSONObject jo = new JSONObject();
jo.put("Description", r5.getString("content"));
jo.put("Id", r5.getString("id"));
jo.put("Issent",r5.getString("issent"));
ja.put(jo);
}
ret= final.put("List", ja).toString();
Try the above one. Should work.
I suggest
JSONObject jo = new JSONObject();
JSONArray ja = new JSONArray();
try {
Statement ac = DBL.getConnection().createStatement();
ResultSet r5 = ac.executeQuery("Select * from msg");
while(r5.next()){
System.out.println("Value taken from database"+r5.getString("content"));
JSONObject element = new JSONObject();
element.put("Description", r5.getString("content"));
element.put("Id", r5.getString("id"));
element.put("Issent",r5.getString("issent"));
ja.put(element);
}
jo.put( "List", ja );
System.out.println(jo.toString());
ret= jo.toString();
You are asking Jackson to parse a StudentList. Tell it to parse a List (of students) instead. Since List is generic you will typically use a TypeReference
List<Student> participantJsonList = mapper.readValue(jsonString, new TypeReference<List<Student>>(){});
For any one who looks for answer yet:
1.Add jackson-databind library to your build tools like Gradle or Maven
2.in your Code:
ObjectMapper mapper = new ObjectMapper();
List<Student> studentList = new ArrayList<>();
studentList = Arrays.asList(mapper.readValue(jsonStringArray, Student[].class));
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
));
Use GSON library for that. Here is the sample code
List<String> foo = new ArrayList<String>();
foo.add("A");
foo.add("B");
foo.add("C");
String json = new Gson().toJson(foo );
Here is the maven dependency for Gson
<dependencies>
<!-- Gson: Java to Json conversion -->
<dependency>
<groupId>com.google.code.gson</groupId>
<artifactId>gson</artifactId>
<version>2.2.2</version>
<scope>compile</scope>
</dependency>
</dependencies>
Or you can directly download jar from here and put it in your class path
http://code.google.com/p/google-gson/downloads/detail?name=gson-1.0.jar&can=4&q=
To send Json to client you can use spring or in simple servlet add this code
response.getWriter().write(json);
You need an external library for this.
JSONArray jsonA = JSONArray.fromObject(mybeanList);
System.out.println(jsonA);
Google GSON is one of such libraries
You can also take a look here for examples on converting Java object collection to JSON string.
In order to have this result:
{"aoColumnDefs":[{"aTargets":[0],"aDataSort":[0,1]},{"aTargets":[1],"aDataSort":[1,0]},{"aTargets":[2],"aDataSort":[2,3,4]}]}
that holds the same data as:
{
"aoColumnDefs": [
{ "aDataSort": [ 0, 1 ], "aTargets": [ 0 ] },
{ "aDataSort": [ 1, 0 ], "aTargets": [ 1 ] },
{ "aDataSort": [ 2, 3, 4 ], "aTargets": [ 2 ] }
]
}
you could use this code:
JSONObject jo = new JSONObject();
Collection<JSONObject> items = new ArrayList<JSONObject>();
JSONObject item1 = new JSONObject();
item1.put("aDataSort", new JSONArray(0, 1));
item1.put("aTargets", new JSONArray(0));
items.add(item1);
JSONObject item2 = new JSONObject();
item2.put("aDataSort", new JSONArray(1, 0));
item2.put("aTargets", new JSONArray(1));
items.add(item2);
JSONObject item3 = new JSONObject();
item3.put("aDataSort", new JSONArray(2, 3, 4));
item3.put("aTargets", new JSONArray(2));
items.add(item3);
jo.put("aoColumnDefs", new JSONArray(items));
System.out.println(jo.toString());
The answer is to use a JSONArray as well, and to dive "deep" into the tree structure:
JSONArray arr = new JSONArray();
arr.put (...); // a new JSONObject()
arr.put (...); // a new JSONObject()
JSONObject json = new JSONObject();
json.put ("aoColumnDefs",arr);
Online : Working code
First create a class to store your values :
class Data{
String id;
String operator;
String value;
}
Then iterate over the json :
JSONArray jsonArr = new JSONArray("[JSON Stirng]");
List<Data> dataList = new ArrayList<>();
for (int i = 0; i < jsonArr.length(); i++) {
JSONObject jsonObj = jsonArr.getJSONObject(i);
Data data = new Data();
data.id = jsonObj.getString("id");
data.operator = jsonObj.getString("operator");
data.value = jsonObj.getString("value");
dataList.add(data);
}
Now dataList has your data!
P.S. : Use getter/setters in Data class
JAR : http://www.java2s.com/Code/Jar/j/Downloadjavajsonjar.htm
- Use any JSON parsor eg: GSON to create an arraylist of this particular json
- Iterate the arraylist
- Save it :)
Iterate through the list in reverse and upon each iteration create a new JsonNode for the list element, add the previous JsonNode as a child to the new JsonNode and overwrite the original reference with the new JsonNode. Rinse and repeat.
Something like...
final String value = "BMW"; // whatever the final "value" is.
final ObjectMapper objectMapper = new ObjectMapper();
ObjectNode json = null;
for (int i = list.size() - 1; i >= 0; i--) {
final String prop = list.get(i);
final ObjectNode objectNode = objectMapper.createObjectNode();
if (json == null) {
objectNode.put(prop, value);
} else {
objectNode.put(prop, json);
}
json = objectNode;
}
Here is the piece of code which you need
package uk.co.vishal;
import com.fasterxml.jackson.core.JsonProcessingException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class Answer {
public static void main(String[] args) throws JsonProcessingException {
List<String> data = new ArrayList<>();
data.add("user");
data.add("car");
data.add("brand");
System.out.println(data.toString());
Map<String, String> mydata = new HashMap<>();
Map<String, JSONObject> newdata = new HashMap<>();
JSONObject result = new JSONObject();
boolean flag = true;
for (int i = data.size() - 1; i >= 0; i--) {
if (flag) {
mydata.put(data.get(i), "BMW");
result = generateJson(mydata);
flag = false;
} else {
newdata.put(data.get(i), result);
result = generateJson(newdata);
newdata.clear();
}
}
System.out.println(result);
/*
* Here is the output:
* {
"user": {
"car": {
"brand": "BMW"
}
}
}
*
* */
}
private static JSONObject generateJson(Map data) {
return new JSONObject(data);
}
}
I hope you will be sorted !!
Using Gson Library it will be very simple.
From JSON String to ArrayList of Object as:
Type listType =
new TypeToken<ArrayList<Student>>(){}.getType();
ArrayList<Student> yourClassList = new Gson().fromJson(jsonArray, listType);
And to Json from Array List of Object as:
ArrayList<Student> sampleList = new ArrayList<Student>();
String json = new Gson().toJson(sampleList);
The Gson Library is more simple to use than JSONObject and JSONArray implementation.
You will have to include the jettison jar in you project and import the required classes.
JSONObject jObject = new JSONObject();
try
{
JSONArray jArray = new JSONArray();
for (Student student : sudentList)
{
JSONObject studentJSON = new JSONObject();
studentJSON.put("name", student.getName());
studentJSON.put("age", student.getAge());
jArray.put(studentJSON);
}
jObject.put("StudentList", jArray);
} catch (JSONException jse) {
jse.printStacktrace();
}