将Dynamic ArrayList转换为Json

时间:2013-01-25 14:57:16

标签: java json playframework-2.0

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

 [
  {"email":"abc@gmail.com"},
  {"email":"xyz@gmail.com"}
 ]

我的控制器操作是

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

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

提前致谢

3 个答案:

答案 0 :(得分: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));
}

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

或手动:

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

不需要Gson。

答案 1 :(得分:0)

您可以使用此库: http://code.google.com/p/google-gson/

这里非常简单的教程: http://www.mkyong.com/java/how-do-convert-java-object-to-from-json-format-gson-api/

或者你可以为你的类或者一个util Json写一个自定义toJson方法(不是什么大不了的)

在你的情况下它应该是那样的(我没有测试它):

public String toJson(List<String> emails) {
    StringBuilder result = new StringBuilder();
    result.append("[");
    result.append("\n");

    for (String s : emails) {
        result.append("{");
        result.append("\"email\":");
        result.append("\"");
        result.append(s);
        result.append("\"");
        result.append("}");
        result.append(",");
        result.append("\n");
    }
    result.append("]");
    return result.toString();
}

答案 2 :(得分:0)

受益于Java 8(我怀疑是更新的Jackson版本):

private static final ObjectMapper mapper = new ObjectMapper();

...

List<Customer> customerList = Model.coll(Customer.class).find().toArray();
ArrayNode emails = mapper.createArrayNode();
customerList.forEach(c -> emails.add(c.email));