標籤:color epo ide bsp override entry return lis enc
1.下載Jar包
http://repo1.maven.org/maven2/com/alibaba/fastjson/
2.將jar包匯入工程3.樣本
package nc.testFastJson;import java.util.ArrayList;import java.util.HashMap;import java.util.LinkedList;import java.util.List;import java.util.Map;import java.util.Map.Entry;import java.util.Set;import com.alibaba.fastjson.JSON;import com.alibaba.fastjson.JSONObject;import com.alibaba.fastjson.TypeReference;public class TestFastJson { public static void main(String[] args) { // java對象 轉 json People p1 = new People("people_1","Male",1); String p1_Json = JSON.toJSONString(p1); System.out.println(p1_Json.toString()); // json 轉 java對象 String p2_Json = "{‘name‘:‘people_2‘,‘sex‘:‘Male‘,‘age‘:2}"; People p2 = JSON.parseObject(p2_Json, People.class); System.out.println(p2.toString()); // java對象LinkedList集合 轉 json LinkedList<People> p_list = new LinkedList<>(); People p3 = new People("people_3","Male",3); People p4 = new People("people_4","Male",4); People p5 = new People("people_5","Male",5); p_list.add(p3); p_list.add(p4); p_list.add(p5); String p_list_Json = JSON.toJSONString(p_list); System.out.println(p_list_Json); // json 轉 java對象List集合 List<People> p_list_2 = JSON.parseArray(p_list_Json, People.class); for (People people : p_list_2) { System.out.println(people.toString()); } // java對象ArrayList 轉 json ArrayList<People> arrayList = new ArrayList<>(); arrayList.add(p3); arrayList.add(p4); arrayList.add(p5); String arrays_json = JSON.toJSONString(arrayList); System.out.println(arrays_json); // json 轉 java對象List集合 List<People> arrayList2 = JSON.parseArray(arrays_json, People.class); for (People people : arrayList2) { System.out.println(people.toString()); } // map 轉 json HashMap<String ,People> map = new HashMap<>(); map.put("p3", p3); map.put("p4", p4); map.put("p5", p5); String map_json = JSON.toJSONString(map); System.out.println(map_json); // json 轉 map Map<String, String> map2 = JSONObject.parseObject(map_json.toString(), new TypeReference<Map<String, String>>(){}); Set<Entry<String, String>> entrySet = map2.entrySet(); for (Entry<String, String> entry : entrySet) { String key = entry.getKey(); String value = entry.getValue(); People p = JSON.parseObject(value, People.class); System.out.println(key+":"+p.toString()); } }}
package nc.testFastJson;public class People { private String name ; private String sex ; private int age ; public String getName() { return name; } public void setName(String name) { this.name = name; } public String getSex() { return sex; } public void setSex(String sex) { this.sex = sex; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } @Override public String toString() { return "People [name=" + name + ", sex=" + sex + ", age=" + age + "]"; } public People() { super(); } public People(String name, String sex, int age) { super(); this.name = name; this.sex = sex; this.age = age; } }
使用FastJson轉化Json格式