conversion of array list to json object string

66,922

Solution 1

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

Solution 2

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);
Share:
66,922
pret
Author by

pret

Updated on October 14, 2020

Comments

  • pret
    pret over 3 years

    I have a model class method which returns a list of objects which contains all the registered user details. I want to fetch the list resturned by all() method and convert the data into JSON object and pass it to the view like a string. How can I do this conversion of this array list to JSON object?

    I was unable to do this by below:

    ObjectMapper mapper = new ObjectMapper();
    JSONObject json = new JSONObject();
    JsonNodeFactory jsonnode = JsonNodeFactory.instance;
    ObjectNode result = new ObjectNode(jsonnode);
    for (int i = 0; i < list.size(); i++) {
        json.put(list.get(i).fname, list.get(i));
        System.out.println(json.get("fname"));
    }
    
    @Entity
    class Mydata extends Model {
    
        @Id
        public Long Id;
        public String fname;
        public String lname;
        public String city;
        public String state;
        /****************** READ/select OPERATION *****************/
        public static Finder < Long, Mydata > finder = new Finder(Long.class, Mydata.class);
    
        public static List < Mydata > all() {
            return finder.all();
        }
        public static void createuser(Mydata user) {
            user.save();
        }
    }