引用
1 2 3 4 5 6
| <dependency> <groupId>com.alibaba</groupId> <artifactId>fastjson</artifactId> <version>1.2.47</version> </dependency>
|
生成JSON
使用JSONObject和JSONArray对象即可。
1 2 3 4 5 6 7 8 9 10 11 12 13 14
| @Test public void whenGenerateJson_thanGenerationCorrect() throws ParseException { JSONArray jsonArray = new JSONArray(); for (int i = 0; i < 2; i++) { JSONObject jsonObject = new JSONObject(); jsonObject.put("AGE", 10); jsonObject.put("FULL NAME", "Doe " + i); jsonObject.put("DATE OF BIRTH", "2016/12/12 12:12:12"); jsonArray.add(jsonObject); } String jsonOutput = jsonArray.toJSONString(); }
|
解析JSON
1 2 3 4 5 6
| @Test public void whenJson_thanConvertToObjectCorrect() { Person person = new Person(20, "John", "Doe", new Date()); String jsonObject = JSON.toJSONString(person); Person newPerson = JSON.parseObject(jsonObject, Person.class);
|
转化JSON
1 2 3 4 5 6 7 8 9
| JSONObject obj = JSON.parseObject("{\"runoob\":\"菜鸟教程\"}");
JSONArray arr = JSON.parseArray("[\"菜鸟教程\",\"RUNOOB\"]\n");
String objStr = JSON.toJSONString(obj);
String arrStr = JSON.toJSONString(arr);
|