1. 导包
<!-- https://mvnrepository.com/artifact/com.alibaba/fastjson 调用者需要转换-->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.58</version>
</dependency>
2. 入门
//对象转换为json字符串,json字符串转换java对象
//JSONObject/JSONArray.toJSONString JSONObject.parseObject JSONArray.parseArray
@Test
public void test() throws Exception{
Person zs = new Person(1L, "zs");
//单个对象--json对象
String jsonObj = JSONObject.toJSONString(zs);
System.out.println(jsonObj);
//集合---json数组
String jsonArray = JSONArray.
toJSONString(Arrays.asList(zs, zs,
new Person(2L, "ls")));
System.out.println(jsonArray);
//json对象--单个对象
Person person = JSONObject.parseObject(jsonObj, Person.class);
System.out.println(person);
//json数组--集合
List<Person> persons = JSONArray.parseArray(jsonArray, Person.class);
System.out.println(persons);
}
网友评论