谷歌html
Gson gson = new Gson(); System.out.println(gson.toJson(1)); // ==> 1 System.out.println(gson.toJson("abcd")); // ==> "abcd" System.out.println(gson.toJson(new Long(10))); // ==> 10 System.out.println(gson.toJson(new int[]{1})); // ==> [1] // Deserialization int int1 = gson.fromJson("1", int.class); Integer Integer1 = gson.fromJson("1", Integer.class); Long Long1 = gson.fromJson("1", Long.class); Boolean Boolean1 = gson.fromJson("false", Boolean.class); String String1 = gson.fromJson("\"abc\"", String.class); String[] StringArr1 = gson.fromJson("[abc]", String[].class);
GitHubgit
阿里巴巴github
String jsonOutput = JSON.toJSONString(listOfPersons); System.out.println(jsonOutput); // [{"AGE":15,"DATE OF BIRTH":1552305572514,"FULL NAME":"John Doe"},{"AGE":20,"DATE OF BIRTH":1552305572514,"FULL NAME":"Janette Doe"}] List<Person> people = JSON.parseArray(jsonOutput, Person.class); System.out.println(people);
Spring Boot默認使用數組
ObjectMapper mapper = new ObjectMapper(); Friend friend = new Friend("yitian", 25); // 寫爲字符串 String text = mapper.writeValueAsString(friend); // 寫爲文件 mapper.writeValue(new File("friend.json"), friend); // 寫爲字節流 byte[] bytes = mapper.writeValueAsBytes(friend); System.out.println(text); // 從字符串中讀取 Friend newFriend = mapper.readValue(text, Friend.class); System.out.println("從字符串中讀取:" + newFriend); // 從字節流中讀取 newFriend = mapper.readValue(bytes, Friend.class); System.out.println("從字節流中讀取:" + newFriend); // 從文件中讀取 newFriend = mapper.readValue(new File("friend.json"), Friend.class); System.out.println("從文件中讀取:" + newFriend);
Jackson快速入門app
出現時間早,不少早期項目使用,目前不推薦使用google
Maven:.net
<dependency> <groupId>net.sf.json-lib</groupId> <artifactId>json-lib</artifactId> <version>2.4</version> <classifier>jdk15</classifier> </dependency> <!--json-lib源碼--> <dependency> <groupId>net.sf.json-lib</groupId> <artifactId>json-lib</artifactId> <version>2.4</version> <classifier>jdk15-sources</classifier> </dependency>
// 建立JSONObject JSONObject jsonObject = new JSONObject(); jsonObject.put("username", "lwc"); jsonObject.put("password", "123"); // 打印:1 System.out.println(jsonObject); // 增長屬性,打印:2 jsonObject.element("sex", "男"); System.out.println(jsonObject); // 根據key返回,打印:3 System.out.println(jsonObject.get("sex")); // 判讀輸出對象的類型 boolean isArray = jsonObject.isArray(); boolean isEmpty = jsonObject.isEmpty(); boolean isNullObject = jsonObject.isNullObject(); // 打印:4 System.out.println("是否數組:" + isArray + " 是否空:" + isEmpty + " 是否空對象:" + isNullObject); // 把JSONArray增長到JSONObject中 JSONArray jsonArray = new JSONArray(); jsonArray.add(0, "lwc"); jsonArray.add(1, "nxj"); // 開始增長 jsonObject.element("student", jsonArray); // 打印:5 System.out.println(jsonObject);