Rhythmk 一步一步学 JAVA(3): java JSON 数据序列化 以及反序列化
package App1.Rhythmk.com; import java.awt.List; import java.awt.font.GlyphJustificationInfo; import com.google.gson.Gson; /* 准备条件: 下载:https://code.google.com/p/google-gson/ */ public class JSON序列化 { /** * @param args */ public static void main(String[] args) { // TODO Auto-generated method stub Serialize(); Deserialize(); /* * 输出: ["rhythmk1","rhythmk2","rhythmk3","rhythmk4"] 1 * ["list1","list2","list3"] {"age":12,"name":"王坤"} List length =3 */ } /* * 序列化 */ public static void Serialize() { String[] strArray = new String[4]; strArray[0] = "rhythmk1"; strArray[1] = "rhythmk2"; strArray[2] = "rhythmk3"; strArray[3] = "rhythmk4"; Gson gson = new Gson(); System.out.println(gson.toJson(strArray)); System.out.println(gson.toJson(1)); List list = new List(); list.add("list1"); list.add("list2"); list.add("list3"); // List 序列化 需要 getItems System.out.println(gson.toJson(list.getItems())); User user = new User(); user.setAge(12); user.setName("王坤"); System.out.println(gson.toJson(user)); } /* * 反序列化 */ public static void Deserialize() { String str = "[\"list1\",\"list2\",\"list3\"]"; String[] arry = new Gson().fromJson(str, String[].class); System.out.print("List length =" + arry.length); } }
一只站在树上的鸟儿,从来不会害怕树枝会断裂,因为它相信的不是树枝,而是它自己的翅膀。与其每天担心未来,不如努力做好现在。