serializing java object to json with auto generated names -
i want create json file out of java objects similar structure:
{"users" :
{"1" : { "ids" : [1,2,3], "names" : ["anton","berta","charlie"] }, {"2" : { "ids" : [4,5,6], "names" : ["dora","emil","friedrich"] },
...and on.
my problem don´t know how generate numbers of second hierarchy. in of tutorials found hierarchy names generated class names or annotations can´t use way create requested names.
is there way without writing huge method generate json stirng "by hand"?
greetz
the code required create each json entry not much:
public static string tojson(int i, list<user> users) { stringbuilder sb = new stringbuilder("{\"").append(i).append("\" : { \"ids\" : ["); (user user : users) sb.append(user.getid()).append(","); sb.setcharat(sb.length() - 1, ']'); sb.append(", \"names\" : [\""); (user user : users) sb.append(user.getname()).append("\",\""); return sb.replace(sb.length() - 2, sb.length(),"] } ,").tostring(); }
with method in place, adding new users list during time period , assigning sequential number each list trivial matter.
here's complete test code , output:
static class user { private final int id; private final string name; public user(int id, string name) { this.id = id; this.name = name; } public int getid() { return id; } public string getname() { return name; } } public static string tojson(int i, list<user> users) { stringbuilder sb = new stringbuilder("{\"").append(i).append("\" : { \"ids\" : ["); (user user : users) sb.append(user.getid()).append(","); sb.setcharat(sb.length() - 1, ']'); sb.append(", \"names\" : [\""); (user user : users) sb.append(user.getname()).append("\",\""); return sb.replace(sb.length() - 2, sb.length(),"] } ,").tostring(); } public static void main(string[] args) {//throws exception { list<user> users = new arraylist<user>(); users.add(new user(1, "anton")); users.add(new user(2, "berta")); users.add(new user(3, "charlie")); system.out.println(tojson(1, users)); }
output:
{"1" : { "ids" : [1,2,3], "names" : ["anton","berta","charlie"] } ,
Comments
Post a Comment