1.下载jar包:
https://www.github.com/alibaba/fastjson/releases
https://www.mvnrepository.com/artifact/com.alibaba/fastjson
2.选取一个版本,点击下载jar
3.在项目下新建lib文件夹,将下载好的jar包拷贝至该目下 :lib/fastjson-1.2.47.jar
4.将jar添加到环境变量下:
右键jar包--> build Path --> add to build path
5.使用
重要的类:JSON
1.将json格式的字符串转化为java中的一个对象
parseObject()
2.将java中的一个对象转化为json格式的字符串
toJSONString()
String p1 = "{"name": "lisi", "age": 18}"; /*Person p = new Person(); String pno = p1.substring(1, p1.length() - 1); System.out.println(pno); String[] split = pno.split(","); String[] name = split[0].split(":"); p.setName(name[1].trim()); String[] age = split[1].split(":"); p.setAge(Integer.parseInt(age[1].trim())); System.out.println(p);*/ Person p = JSON.parseObject(p1,Person.class); System.out.println(p); Person p2 = new Person("laowang", 30); String result = JSON.toJSONString(p2); System.out.println(result); //接受来自js的数据 //给js发送数据 //将js中的数组字符串,转化为java中的List String l1 = "[{"name":"laowang","age":18},{"name":"laoma","age":30}]"; List<Person> list = JSON.parseArray(l1, Person.class); System.out.println(list.get(0)); System.out.println(list.get(1)); //将java的list转化为json格式的数组字符串 List l2 = new ArrayList<>(); l2.add(new Person("zhangsan", 5)); l2.add(new Person("lisi", 6)); String result2 = JSON.toJSONString(l2); System.out.println(result2);