How to convert ArrayList to JSON in Java
•
Java
I have an ArrayList, which has a bunch of domain objects As follows:
Domain [domainId=19,name=a,dnsName=a.com,type=0,flags=0] Domain [domainId=20,name=b,dnsName=b.com,flags=12] Domain [domainId=21,name=c,dnsName=c.com,flags=0] Domain [domainId=22,name=d,dnsName=d.com,flags=0]
My question is how to convert ArrayList to JSON? The data format shall be:
{ "param":{ "domain":[ { "domid":19,"name":"a","dnsname":"a.com","type":0,"flags": },... ] }
Solution
I'm not sure if it's exactly what you need, but you can use the gson Library (link) to convert ArrayList to JSON
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 traverse the ArrayList and build JSON from each domain object 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(); }
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
二维码