Json和Map互转,三个包(org.json/net.sf.json/com.google.gson)
程序员文章站
2022-04-28 12:37:03
目前使用的(org.json/net.sf.json/com.google.gson)这三种json-map互转,其他包的以后在补充。。。。。。。。。。。。。。 导入的jar有: commons-beanutils-1.6.1.jar commons-lang-2.1.jar ezmorph-1.0 ......
目前使用的(org.json/net.sf.json/com.google.gson)这三种json-map互转,其他包的以后在补充。。。。。。。。。。。。。。
导入的jar有:
commons-beanutils-1.6.1.jar
commons-lang-2.1.jar
ezmorph-1.0.3.jar
jackson-all-1.8.5.jar
gson-2.2.4.jar
json-lib-2.2.2-jdk15.jar
json.jar
/** * */ package map2json; import java.util.hashmap; import java.util.iterator; import java.util.linkedhashmap; import java.util.map; import java.util.map.entry; import net.sf.json.jsonarray; import com.google.gson.gson; /** * @author hy * @date 2019-02-25 15:45:35 * */ public class map2json { public static void main(string[] args) { //map2jsonstr1(); //map2jsonstr2(); map2jsonstr3(); } //net.sf.json包 public static void map2jsonstr1() { map<string, object> map =new linkedhashmap<string, object>(); map.put("1", "a"); map.put("2", "b"); map.put("3", "c"); map.put("4", "d"); map.put("5", "e"); map.put("6", new string[]{"aa","bb"}); //多个不同包的同名类,需要指明指哪个包里的 net.sf.json.jsonobject jo = net.sf.json.jsonobject.fromobject(map); system.out.println(jo.tostring()); //数组 jsonarray json =jsonarray.fromobject(map); system.out.println(json.tostring()); //将json数据再转回map net.sf.json.jsonobject myjson = net.sf.json.jsonobject.fromobject(map); @suppresswarnings("unchecked") map<object,object> m = myjson; for (entry<object, object > entry : m.entryset()) { system.out.println(entry.getkey().tostring()+":"+entry.getvalue().tostring()); } } // org.json包 public static void map2jsonstr2() { map<string, string> map =new linkedhashmap<string, string>(); map.put("1", "a"); map.put("2", "b"); map.put("3", "c"); map.put("4", "d"); map.put("5", "e"); //org.json org.json.jsonobject js =new org.json.jsonobject(map); system.out.println(js.tostring()); map<object, object> ma = new hashmap<>(); @suppresswarnings("rawtypes") iterator it = js.keys(); while(it.hasnext()){ string key = (string) it.next(); //得到value的值 object value = js.get(key); // system.out.println(key+":"+valstr); ma.put(key,value.tostring()); } for (entry<object, object> mp : ma.entryset()) { system.out.println(mp.getkey()+":"+mp.getvalue()); } } @suppresswarnings("unchecked") //com.google.gson public static void map2jsonstr3() { map<string, string> map =new linkedhashmap<string, string>(); map.put("1", "a"); map.put("2", "b"); map.put("3", "c"); map.put("4", "d"); map.put("5", "e"); gson gson = new gson(); string jsonstr = gson.tojson(map); system.out.println(jsonstr); map<object, object> ma =new hashmap<>(); ma = gson.fromjson(jsonstr, map.class); for (entry<object, object> mp : ma.entryset()) { system.out.println(mp.getkey()+":"+mp.getvalue()); } } }
上一篇: 厕所串串,吃的就是这个味!
下一篇: 浅析C# Dictionary实现原理