首页 > 代码库 > Gson应用:利用map和list来拼装Json消息
Gson应用:利用map和list来拼装Json消息
1 2 3 import java.util.ArrayList; 4 import java.util.HashMap; 5 import java.util.List; 6 import java.util.Map; 7 import com.google.gson.Gson; 8 9 public class GsonTest { 10 11 public static void main(String[] args) { 12 13 Gson g = new Gson(); 14 Map<String,Object> map = new HashMap<String,Object>(); 15 //添加两个普通节点 16 map.put("a","1"); 17 map.put("b",2); 18 19 //添加一个list1 => "list1":[{"c":"3","d":4}] 20 Map<String,Object> m5 = new HashMap<String,Object>(); 21 List<Object> l = new ArrayList<Object>(); 22 m5.put("c","3"); 23 m5.put("d",4); 24 l.add(m5); 25 map.put("list1",l); 26 27 //添加一个map1 =>"map1":{"e":"5","f":"6"} 28 Map<String,Object> m2 = new HashMap<String,Object>(); 29 m2.put("e","5"); 30 m2.put("f","6"); 31 map.put("map1",m2); 32 33 //添加一个list2 => "list2":[{"g":"7","h":8},{"g":"9","h":10}] 34 List<Object> l2 = new ArrayList<Object>(); 35 Map<String,Object> m3 = new HashMap<String,Object>(); 36 Map<String,Object> m4 = new HashMap<String,Object>(); 37 m3.put("g","7"); 38 m3.put("h",8); 39 m4.put("g","9"); 40 m4.put("h",10); 41 l2.add(m3); 42 l2.add(m4); 43 map.put("list2",l2); 44 45 46 //添加一个map2 => "map2":{"i":"5","j":[{"j":"5","k":"5"}],"l":{"j":"5","k":"5"}} 47 Map<String,Object> m6 = new HashMap<String,Object>(); 48 List<Object> l3 = new ArrayList<Object>(); 49 Map<String,Object> m7 = new HashMap<String,Object>(); 50 m6.put("i","5"); 51 52 m7.put("j","5"); 53 m7.put("k","5"); 54 m6.put("l",m7); 55 56 l3.add(m7); 57 m6.put("j",l3); 58 map.put("map2",m6); 59 60 61 //转换成JSON格式内容 62 String s = g.toJson(map); 63 System.out.println(s); 64 65 } 66 67 }
输出
{"list1":[{"c":"3","d":4}],"a":"1","b":2,"map2":{"i":"5","j":[{"j":"5","k":"5"}],"l":{"j":"5","k":"5"}},"map1":{"e":"5","f":"6"},"list2":[{"g":"7","h":8},{"g":"9","h":10}]}
1 { 2 "list1":[ 3 { 4 "c":"3", 5 "d":4 6 } 7 ], 8 "a":"1", 9 "b":2, 10 "map2":{ 11 "i":"5", 12 "j":[ 13 { 14 "j":"5", 15 "k":"5" 16 } 17 ], 18 "l":{ 19 "j":"5", 20 "k":"5" 21 } 22 }, 23 "map1":{ 24 "e":"5", 25 "f":"6" 26 }, 27 "list2":[ 28 { 29 "g":"7", 30 "h":8 31 }, 32 { 33 "g":"9", 34 "h":10 35 } 36 ] 37 }
Gson应用:利用map和list来拼装Json消息
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。