版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/xiaoshuxgh/article/details/80065327
private static JSONObject buildJson(int userid, List<GroupElement> groups,int termimal,long t,String mdkey) { JSONObject obj = null; try { obj = new JSONObject(); JSONArray jsonArr = new JSONArray(); JSONObject infojson = new JSONObject(); obj.put("userid",userid); obj.put("termimal",termimal); obj.put("t",t); obj.put("mdkey",mdkey); JSONObject jsonObj= null; if (groups != null) { for (GroupElement groupElement : groups) { jsonObj = new JSONObject(); jsonObj.put("id", Long.parseLong(groupElement.getGroupid())); jsonObj.put("name",groupElement.getTitle()); jsonArr.put(jsonObj) ; infojson.put("data",jsonArr); } } obj.put("info",infojson); Log.e("obj", "buildJson: "+obj); } catch (JSONException e) { try { DBLog.writexiangyuanMesage("GroupSync JSONException e:"+e.getMessage()); }catch (Exception ex){ e.printStackTrace(); } e.printStackTrace(); } return obj; }
拼完后是这样的(数据是随便写的):
{"userid":1,"termimal":1,"t":100000,"mdkey":"dede","info":{"data":[{"id":10002,"name":"哦哦哦"},{"id":10002,"name":"哦哦哦"},{"id":10002,"name":"哦哦哦"}]}}
用new Gson().toJson(user),发现简单省事,手动添加数据写的(主要在意格式,忽略数据的细节问题)
public class User { private int age; private int id; private String name; private String school; private Result info; public int getAge() { return age; } public void setAge(int age) { this.age = age; } public int getId() { return id; } public void setId(int id) { this.id = id; } public String getName() { return name == null ? "" : name; } public void setName(String name) { this.name = name; } public String getSchool() { return school == null ? "" : school; } public void setSchool(String school) { this.school = school; } public Result getInfo() { return info; } public void setInfo(Result info) { this.info = info; } public static class Data { private String obj; private int num; public String getObj() { return obj == null ? "" : obj; } public void setObj(String obj) { this.obj = obj; } public int getNum() { return num; } public void setNum(int num) { this.num = num; } } public static class Result { private List<Data> data; public List<Data> getData() { if (data == null) { return new ArrayList<>(); } return data; } public void setData(List<Data> data) { this.data = data; } } }
List<User.Data> strs = new ArrayList<>(); User.Data data = new User.Data(); data.setNum(99); data.setObj("忘"); strs.add(data); data.setNum(98); data.setObj("哦"); strs.add(data); User user = new User(); user.setAge(1); user.setId(0); user.setName("张"); user.setSchool("a1"); User.Result result = new User.Result(); result.setData(strs); user.setInfo(result); Log.e("onCreate==", new Gson().toJson(user));
结果:onCreate==: {"age":1,"id":0,"info":{"data":[{"num":98,"obj":"哦"},{"num":98,"obj":"哦"}]},"name":"张","school":"a1"}
完成。之前的写过的,突发奇想整理一下。