Converting Dynamic ArrayList to Json

java, json, playframework-2.0

Solution

Why use another JSON ser/des lib? Play has one built-in (a wrapper around jackson - which is really fast).

Starting from your code:

public static Result apiCustomers(){
    List<Customer> customerList = Model.coll(Customer.class).find().toArray();
    List<String> emails = new ArrayList<String>();

    for(Customer c : customerList){
        emails.add(c.email);
    }

    return ok(Json.toJson(emails));
}

This uses some defaults but should be enough.

Or manually:

public static Result apiCustomers(){
        ArrayNode arrayNode = new ArrayNode(JsonNodeFactory.instance);

        List<Customer> customerList = Model.coll(Customer.class).find().toArray();

        for(Customer c : customerList){
            ObjectNode mail = Json.newObject();
            mail.put("email", c.email);
            arrayNode.add(mail);
        }

        return ok(arrayNode);
}

No need for Gson.

Problem

I want to convert an array list to json string of a specific format. I get all the users emails in an array list and want to convert it into the following format of JSON. ``` [ {"email":"abc@gmail.com"}, {"email":"xyz@gmail.com"} ] ``` My controller action is ``` public static Result apiCustomers(){ List<Customer> customerList = Model.coll(Customer.class).find().toArray(); List<String> emails = new ArrayList<String>(); for(Customer c : customerList){ emails.add(c.email); } //ObjectNode result = Json.newObject(); //result.put("emails", Json.toJson(emails)); return ok(); } ``` How can I convert the emails list to the above json format? Thanks in advance

Original source