如何在 Java 中将 Arraylist 转换为 Json

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/25771822/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-11 01:06:26  来源:igfitidea点击:

How to convert Arraylist to Json in Java

javajson

提问by typeof programmer

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]
Domain [domainId=20, name=b, dnsName=b.com, type=0, flags=12]
Domain [domainId=21, name=c, dnsName=c.com, type=0, flags=0]
Domain [domainId=22, name=d, dnsName=d.com, type=0, flags=0]

My question is how to convert the ArrayListto JSON? The data format should be:

我的问题是如何将 转换ArrayList为 JSON?数据格式应为:

{  
"param":{  
  "domain":[  
    {  
      "domid":19,
      "name":"a",
      "dnsname":"a.com",
      "type":0,
      "flags":
    },
    ...
  ]
}

采纳答案by nem035

Not sure if it's exactly what you need, but you can use the GSONlibrary (Link) for ArrayListto JSONconversion.

不知道这是你需要什么,但你可以使用GSON库(链接)用于ArrayListJSON转换。

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 ArrayListand build a JSONfrom individual Domainobjects in the list

如果由于某种原因你觉得它更方便,你也可以遍历列表中的单个对象ArrayList并构建一个JSONDomain

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