例1:将map对象添加一次元素(包括字符串对、数组),转换成json对象一次。
代码:
运行结果:
{"name":"reiz"}{"initial":"R","likes":["JavaScript","Skiing","Apple Pie"],"name":"reiz"}{"ingredients":{"apples":"3kg","pastry":"2.4kg","bestEaten":"outdoors","sugar":"1kg"},"initial":"R","likes":["JavaScript","Skiing","Apple Pie"],"name":"reiz"}(需要用到的包可在官网下载:http://.json; import java.util.Collection;import java.util.Map;import java.util.Map.Entry; import net.sf.json.JSONArray;import net.sf.json.JSONObject; public class jsonToListandMap { public static void main(String[] args) { // TODO Auto-generated method stub String listStr = "[\"apple\",\"orange\"]"; Collection<String> strlist = JSONArray.toCollection(JSONArray.fromObject(listStr)); for (String str : strlist) { System.out.println(str); } String mapStr = "{\"age\":30,\"name\":\"Michael\",\"baby\":[\"Lucy\",\"Lily\"]}"; Map<String, Object> map = (Map) JSONObject.toBean(JSONObject .fromObject(mapStr), Map.class); for (Entry<String, Object> entry : map.entrySet()) { System.out.println(entry.getKey() + " " + entry.getValue()); } } }
运行结果:
apple
orange
name Michael
age 30
baby [Lucy, Lily]
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。