9

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 ArrayList to JSON? The data format should be:

{  
"param":{  
  "domain":[  
    {  
      "domid":19,
      "name":"a",
      "dnsname":"a.com",
      "type":0,
      "flags":
    },
    ...
  ]
}
nem035
  • 34,790
  • 6
  • 87
  • 99
typeof programmer
  • 1,509
  • 4
  • 22
  • 34
  • http://stackoverflow.com/questions/5166592/convert-normal-java-array-or-arraylist-to-json-array-in-android – dazito Sep 10 '14 at 17:49

1 Answers1

28

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();
}
nem035
  • 34,790
  • 6
  • 87
  • 99
  • 4
    I know it's an old comment, but if anyone get stuck at this point: new Gson().fromJson(json, new TypeToken>(){}.getType()); – wyzard Oct 31 '17 at 09:56