conversion of the array list to json

advertisements

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


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