将Dynamic ArrayList转换为Json

Uma*_*air 2 java json playframework-2.0

我想将数组列表转换为特定格式的json字符串.我将所有用户的电子邮件都放在数组列表中,并希望将其转换为以下格式的JSON.

 [
  {"email":"abc@gmail.com"},
  {"email":"xyz@gmail.com"}
 ]
Run Code Online (Sandbox Code Playgroud)

我的控制器动作是

 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();
}
Run Code Online (Sandbox Code Playgroud)

如何将电子邮件列表转换为上述json格式?

提前致谢

hcu*_*ura 6

为什么要使用另一个JSON ser/des lib?Play有一个内置(Jackson周围的包装 - 非常快).

从您的代码开始:

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));
}
Run Code Online (Sandbox Code Playgroud)

这使用了一些默认值,但应该足够了.

或手动:

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);
}
Run Code Online (Sandbox Code Playgroud)

不需要Gson.