pom.xml
<dependency> <groupId>com.alibaba</groupId> <artifactId>fastjson</artifactId> <version>1.2.68</version> </dependency>
简单java类
package com.pengshiyu.bean; public class Person { private String name; private int age ; public String getName() { return name; } public void setName(String name) { this.name = name; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } @Override public String toString() { return "Person{" + "name='" + name + '\'' + ", age=" + age + '}'; } }
使用示例
package com.pengshiyu.demo; import com.alibaba.fastjson.JSON; import com.pengshiyu.bean.Person; public class JsonDemo { public static void main(String[] args) { Person person = new Person(); person.setAge(23); person.setName("Tom"); //序列化 String text = JSON.toJSONString(person); System.out.println(text); // {"age":23,"name":"Tom"} //反序列化 Person newPerson = JSON.parseObject(text, Person.class); System.out.println(newPerson); // Person{name='Tom', age=23} } }
不定义实体类转换
package com.pengshiyu; import com.alibaba.fastjson.JSONObject; public class FastJsonDemo { public static void main(String[] args) { String userString = "{\"age\":1, \"name\": \"Tom\"}"; JSONObject userJson = JSONObject.parseObject(userString); System.out.println(userJson.get("name")); // Tom } }