目录
(1)语法
示例:
(2)构成要素
1.对象{ } 2.数组[ ] 3.属性名:属性值 4.逗号(多个数据之间由逗号分隔)
(3)属性值类型种类
字符串、数字、布尔值、null、数组、对象
步骤1:Json解析框架fastjson-1.2.47.jar【使用maven的pom依赖管理】
步骤2:创建maven工程,并创建标准目录
步骤3:实现java对象转成Json字符串
步骤3.1 创建Java对象
- package org.example;
-
- import java.util.List;
-
- public class Student {
- private String name;
- private int age;
- private List
love; - public Student() {
- }
-
- public Student(String name, int age, List
love) { - this.name = name;
- this.age = age;
- this.love = love;
- }
-
- 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;
- }
-
- public List
getLove() { - return love;
- }
-
- public void setLove(List
love) { - this.love = love;
- }
- }
步骤3.2 pom引入fastjson的依赖
- <dependency>
- <groupId>com.alibabagroupId>
- <artifactId>fastjsonartifactId>
- <version>1.2.47version>
- dependency>
步骤3.3 测试类转换
- package org.example;
-
- import com.alibaba.fastjson.JSON;
-
- import java.util.Arrays;
- import java.util.List;
-
- public class Test {
- public static void main(String[] args) {
- String []array = new String[]{"乔尼","杰洛","大总统"};
- List
list = Arrays.asList(array); -
- //1.构建对象
- Student student = new Student("jojo",1,list);
-
- String s = JSON.toJSON(student).toString();
- System.out.println(s);
-
- }
- }
效果:
步骤4:实现JSON字符串转成Java对象
- package org.example;
-
- import com.alibaba.fastjson.JSON;
-
- import java.util.Arrays;
- import java.util.List;
-
- public class Test {
- public static void main(String[] args) {
- //步骤1:定义Json字符串
- String st = new String("{\"love\":[\"乔尼\",\"杰洛\",\"大总统\"],\"name\":\"jojo\",\"age\":1}\n");
- //步骤2:将字符串转换成Java对象【通过parseObject方法】
- Student student = JSON.parseObject(st,Student.class);
- //步骤3:输出Java对象中的方法
- System.out.println(student.getName());
- System.out.println(student.getAge());
- System.out.println(student.getLove());
- }
- }
效果: