How to convert Arraylist to Json in Java

后端 未结 1 719
无人共我
无人共我 2020-12-16 23:39

I have an arraylist, the arraylist holds a bunch of Domain object. It\'s like below showed:

Domain [domainId=19, name=a, dnsName=a.com, type=0, flags=0]
Doma         


        
相关标签:
1条回答
  • 2020-12-17 00:13

    Not sure if it's exactly what you need, but you can use the GSON library (Link) for ArrayList to JSON conversion.

    ArrayList<String> list = new ArrayList<String>();
    list.add("str1");
    list.add("str2");
    list.add("str3");
    String json = new Gson().toJson(list);
    

    Or in your case:

    ArrayList<Domain> list = new ArrayList<Domain>();
    list.add(new Domain());
    list.add(new Domain());
    list.add(new Domain());
    String json = new Gson().toJson(list);
    

    If for some reason you find it more convenient, you can also iterate through the ArrayList and build a JSON from individual Domain objects in the list

    String toJSON(ArrayList<Domain> list) {
        Gson gson = new Gson();
        StringBuilder sb = new StringBuilder();
        for(Domain d : list) {
            sb.append(gson.toJson(d));
        }
        return sb.toString();
    }
    
    0 讨论(0)
提交回复
热议问题