JSON使用方法

1.JSON

JSON(JavaScript Objection Notation)是一种轻量级的数据交互格式,且采用完全独立于语言的文本格式,许多语言提供了对JSON的支持(C,C++,Java,JavaScript,Perl,Python等)。

数据交换指的是客户端和服务器直接业务数据的传递格式

特点:
• JSON 指的是 JavaScript 对象表示法(JavaScript Object Notation)
• JSON 是轻量级的文本数据交换格式
• JSON 独立于语言:JSON 使用 Javascript语法来描述数据对象,但是 JSON 仍然独立于语言和平台。JSON 解析器和 JSON 库支持许多不同的编程语言。 目前非常多的动态(PHP,JSP,.NET)编程语言都支持JSON。
• JSON 具有自我描述性,更易理解

1.1JSON语法规则

• 数据以键值对组成
• 数据由逗号分隔
• 大括号 {} 保存对象
• 中括号 [] 保存数组,数组可以包含多个对象

1.2JSON值

JSON 值可以是:
• 数字(整数或浮点数)
• 字符串(在双引号中)
• 逻辑值(true 或 false)
• 数组(在中括号中)
• 对象(在大括号中)
• null

1.3JSON数组

JSON 数组在中括号 [] 中书写:
数组可包含多个对象:

[
    { key1 : value1-1 , key2:value1-2 }, 
    { key1 : value2-1 , key2:value2-2 }, 
    { key1 : value3-1 , key2:value3-2 }, 
    ...
    { keyN : valueN-1 , keyN:valueN-2 }, 
]


{ 
	"sites": [ 
	{ "name":"菜鸟教程" , "url":"www.runoob.com" },
	 { "name":"google" , "url":"www.google.com" }, 
	{ "name":"微博" , "url":"www.weibo.com" } 
	] 
}

1.4JSON对象

{ "name":"runoob", "alexa":10000, "site":null }
  • JSON 对象使用在大括号({})中书写。
  • 对象可以包含多个 key/value(键/值)对。
  • key 必须是字符串,value 可以是合法的 JSON 数据类型(字符串, 数字, 对象, 数组, 布尔值或 null)。
  • key 和 value 中使用冒号(:)分割。
  • 每个 key/value 对使用逗号(,)分割。

1.5JSON文件

• JSON 文件的文件类型是 .json
• JSON 文本的 MIME 类型是 application/json

1.1JSON的两个常用方法

JSON文件存在有两种形式:

  1. 对象的形式存在,我们叫它JSON对象
    一般我们要操作JSON中的数据的时候,需要JSON对象的格式
  2. 字符串的形式存在,我们叫它JSON字符串
    一般我们要在客户端和服务器直接进行数据交互的时候,使用JSON字符串
JSON.stringify() //把json对象转换成json字符串
JSON.parse()   //把json字符串转换成json对象

2.Gson

准备工作

@NoArgsConstructor
@AllArgsConstructor
@Data
public class Student {

    private String name;
    private Integer age;
    private String gender;

}

2.1JavaBean 和 json字符串 互转

    /**
     * 测试 JavaBean 和 json 互转
     */
    @Test
    public void test1(){
        Student student = new Student("韩同学", 18, "女");
        //创建Gson对象实例
        Gson gson = new Gson();
        //toJson方法可以把java对象转换为json字符串
        String studentJsonString = gson.toJson(student);
        System.out.println(studentJsonString); // {"name":"韩同学","age":18,"gender":"女"}

        //fromJson 把 json字符串转为 Java 对象
        String jsonStr = "{\"name\":\"韩同学\",\"age\":18,\"gender\":\"女\"}"; //即是studentJsonString
        Student student1 = gson.fromJson(jsonStr, Student.class);
        System.out.println(student1); //Student{name='韩同学', age=18, gender='女'}

    }

2.2ArrayList 和 json字符串 互转


```java
    /**
     * list 和 json 互转
     */
    @Test
    public void test2(){
        ArrayList<Student> studentList = new ArrayList<>();
        studentList.add(new Student("韩同学",18,"男"));
        studentList.add(new Student("王同学",18,"女"));

        Gson gson = new Gson();

        // 把 ArrayList 转换为 json 字符串
        String studentListString = gson.toJson(studentList);
        System.out.println(studentListString); // [{"name":"韩同学","age":18,"gender":"男"},{"name":"王同学","age":18,"gender":"女"}]

        // 把 json 字符串 转换为 ArrayList
        // new TypeToken<ArrayList<Student>>(){}.getType()
        List<Student> list = gson.fromJson(studentListString, new TypeToken<ArrayList<Student>>() {}.getType());
        System.out.println(list);//[Student{name='韩同学', age=18, gender='男'}, Student{name='王同学', age=18, gender='女'}]
        Student student = list.get(0);
        System.out.println(student);//Student{name='韩同学', age=18, gender='男'}
    }

2.3map 和 json字符串 互转

    @Test
    public void test3(){
        HashMap<Integer, Object> studentMap = new HashMap<>();
        studentMap.put(1,new Student("韩同学",18,"男"));
        studentMap.put(2,new Student("王同学",18,"女"));

        Gson gson = new Gson();
        // 将 map 转为 Json 字符串
        String studentMapJsonString = gson.toJson(studentMap);
        System.out.println(studentMapJsonString); //{"1":{"name":"韩同学","age":18,"gender":"男"},"2":{"name":"王同学","age":18,"gender":"女"}}

        // 将 Json 字符串 转为 map
        HashMap<Integer, Object> studentMap2 = gson.fromJson(studentMapJsonString, new TypeToken<HashMap<Integer, Student>>() {}.getType());
        System.out.println(studentMap2);//{1=Student{name='韩同学', age=18, gender='男'}, 2=Student{name='王同学', age=18, gender='女'}}

        Student student = (Student) studentMap2.get(1);
        System.out.println(student);//Student{name='韩同学', age=18, gender='男'}
    }

3.FastJson

FastJson对于json格式字符串的解析主要用到以下三个类:

  1. JSON:FastJson的解析器,用于JSON格式字符串和JSON对象以及JavaBean之间的转换
  2. JSONObject:FastJson提供的json对象
  3. JSONArray:FastJson提供json数组对象

JSONObject常用方法:

  1. put(String key, Object value)方法,在JSONObject对象中设置键值对在,在进行设值得时候,key是唯一的,如果用相同的key不断设值得时候,保留后面的值。
  2. Object get(String key) :根据key值获取JSONObject对象中对应的value值,获取到的值是Object类型,需要手动转化为需要的数据类型
  3. int size():获取JSONObject对象中键值对的数量
  4. boolean isEmpty():判断该JSONObject对象是否为空
  5. containsKey(Object key):判断是否有需要的key值
  6. boolean containsValue(Object value):判断是否有需要的value值
  7. JSONObject getJSONObject(String key):如果JSONObjct对象中的value是一个JSONObject对象,即根据key获取对应的JSONObject对象;
  8. JSONArray getJSONArray(String key) :如果JSONObject对象中的value是一个JSONObject数组,既根据key获取对应的JSONObject数组;
  9. Object remove(Object key):根据key清除某一个键值对。
    由于JSONObject是一个map,它还具有map特有的两个方法:
  10. Set keySet() :获取JSONObject中的key,并将其放入Set集合中
  11. Set<Map.Entry<String, Object>> entrySet():在循环遍历时使用,取得是键和值的映射关系,Entry就是Map接口中的内部接口
  12. toJSONString() /toString():将JSONObject对象转换为json的字符串
  13. JSON.parseObject(String str)是将str转化为相应的JSONObject对象,其中str是“键值对”形式的json字符串,转化为JSONObject对象之后就可以使用其内置的方法,进行各种处理了。

准备工作
Student类、Course类、Teacher类

@NoArgsConstructor
@AllArgsConstructor
@Data
public class Student {
    private String studentName;
    private Integer studentAge;
}

@NoArgsConstructor
@AllArgsConstructor
@Data
public class Course {

    private String courseName;
    private Integer code;
}
@Data
@AllArgsConstructor
@NoArgsConstructor
public class Teacher {

    private String teacherName;
    private Integer teacherAge;
    private Course course;
    private ArrayList<Student> students;
    
    
}

定义三个json格式的字符串

    //json字符串-简单对象型
    private static final String  JSON_OBJ_STR = "{\"studentName\":\"lily\",\"studentAge\":12}";

    //json字符串-数组类型
    private static final String  JSON_ARRAY_STR = "[{\"studentName\":\"lily\",\"studentAge\":12},{\"studentName\":\"lucy\",\"studentAge\":15}]";

    //json字符串-复杂类型
    private static final String  COMPLEX_JSON_STR = "{\"teacherName\":\"crystall\",\"teacherAge\":27,\"course\":{\"courseName\":\"english\",\"code\":1270},\"students\":[{\"studentName\":\"lily\",\"studentAge\":12},{\"studentName\":\"lucy\",\"studentAge\":15}]}";

3.1json格式字符串 和 json对象 互转

3.1.1json字符串-简单对象 和 JSONObject 互转
    /**
     * json字符串-简单对象型 到 JSONObject 的转换
     */
    @Test
    public void testJSONStrToJSONObject() {

        // JSONObject.parseObject() 将字符串转换成JSONObject
        JSONObject jsonObject = JSONObject.parseObject(JSON_OBJ_STR);
        System.out.println(jsonObject); //{"studentAge":12,"studentName":"lily"}
        String studentName = jsonObject.getString("studentName");
        System.out.println(studentName);//lily
        System.out.println("studentName:  " + jsonObject.getString("studentName") + ";" + "  studentAge:  "
                + jsonObject.getInteger("studentAge"));//studentName:  lily;  studentAge:  12

    }

    /**
     * JSONObject到 json字符串-简单对象型的转换
     */
    @Test
    public void testJSONObjectToJSONStr() {

        // JSONObject.parseObject() 将字符串转换成JSONObject
        JSONObject jsonObject = JSONObject.parseObject(JSON_OBJ_STR);

        //已知JSONObject,目标要转换为json字符串
        // 第一种方式
        String jsonString = JSONObject.toJSONString(jsonObject);//{"studentAge":12,"studentName":"lily"}

        // 第二种方式
        //String jsonString = jsonObject.toJSONString();
        System.out.println(jsonString);
    }
3.1.2json字符串-数组类型 和 JSONArray 互转
  /**
     * json字符串-数组类型 到 JSONArray的转换
     */
    @Test
    public void testJSONStrToJSONArray() {

        JSONArray jsonArray = JSONArray.parseArray(JSON_ARRAY_STR);

        System.out.println(jsonArray);//[{"studentAge":12,"studentName":"lily"},{"studentAge":15,"studentName":"lucy"}]

        //遍历方式1
        int size = jsonArray.size();
        for (int i = 0; i < size; i++) {

            JSONObject jsonObject = jsonArray.getJSONObject(i);
            System.out.println("studentName:  " + jsonObject.getString("studentName") + ":" + "  studentAge:  "
                    + jsonObject.getInteger("studentAge"));
        }

        //遍历方式2
        for (Object obj : jsonArray) {

            JSONObject jsonObject = (JSONObject) obj;
            System.out.println("studentName:  " + jsonObject.getString("studentName") + ":" + "  studentAge:  "
                    + jsonObject.getInteger("studentAge"));
        }
    }

    /**
     * JSONArray到json字符串-数组类型的转换
     */
    @Test
    public void testJSONArrayToJSONStr() {

        //已知JSONArray,目标要转换为json字符串
        JSONArray jsonArray = JSONArray.parseArray(JSON_ARRAY_STR);
        //第一种方式
        String jsonString = JSONArray.toJSONString(jsonArray);//[{"studentAge":12,"studentName":"lily"},{"studentAge":15,"studentName":"lucy"}]

        // 第二种方式
        //String jsonString = jsonArray.toJSONString(jsonArray);
        System.out.println(jsonString);
    }

3.1.3json字符串-复杂类型 和 JSONObject 互转
   /**
     * json字符串-复杂类型 到 JSONObject 的转换
     */
    @Test
    public void testComplexJSONStrToJSONObject() {

        JSONObject jsonObject = JSONObject.parseObject(COMPLEX_JSON_STR);

        System.out.println(jsonObject);
        /*
        {"teacherAge":27,"teacherName":"crystall","course":{"courseName":"english","code":1270},
        "students":[{"studentAge":12,"studentName":"lily"},{"studentAge":15,"studentName":"lucy"}]}
         */

        String teacherName = jsonObject.getString("teacherName");
        Integer teacherAge = jsonObject.getInteger("teacherAge");

        System.out.println("teacherName:  " + teacherName + "   teacherAge:  " + teacherAge); //teacherName:  crystall   teacherAge:  27

        JSONObject jsonObjectCourse = jsonObject.getJSONObject("course");
        //获取JSONObject中的数据
        String courseName = jsonObjectCourse.getString("courseName");
        Integer code = jsonObjectCourse.getInteger("code");

        System.out.println("courseName:  " + courseName + "   code:  " + code); //courseName:  english   code:  1270

        JSONArray jsonArrayStudents = jsonObject.getJSONArray("students");

        //遍历JSONArray
        for (Object object : jsonArrayStudents) {

            JSONObject jsonObjectone = (JSONObject) object;
            String studentName = jsonObjectone.getString("studentName");
            Integer studentAge = jsonObjectone.getInteger("studentAge");

            System.out.println("studentName:  " + studentName + "   studentAge:  " + studentAge);
            /*
            studentName:  lily   studentAge:  12
stud        entName:  lucy   studentAge:  15
             */
        }
    }

    /**
     * 复杂JSONObject到 json字符串-复杂类型 的转换
     */
    @Test
    public void testJSONObjectToComplexJSONStr() {

        //复杂JSONObject,目标要转换为json字符串
        JSONObject jsonObject = JSONObject.parseObject(COMPLEX_JSON_STR);

        //第一种方式
        //String jsonString = JSONObject.toJSONString(jsonObject);

        //第二种方式
        String jsonString = jsonObject.toJSONString();
        /*
        {"teacherAge":27,"teacherName":"crystall","course":{"courseName":"english","code":1270},
        "students":[{"studentAge":12,"studentName":"lily"},{"studentAge":15,"studentName":"lucy"}]}
         */
        System.out.println(jsonString);

    }

3.2json格式字符串 和 javaBean 互转

3.2.1json字符串-简单对象 和 JavaBean 互转
    /**
     * json字符串-简单对象 到 JavaBean 之间的转换
     */
    @Test
    public void testJSONStrToJavaBeanObj() {

        //第一种方式
        JSONObject jsonObject = JSONObject.parseObject(JSON_OBJ_STR);
        System.out.println(jsonObject);//{"studentAge":12,"studentName":"lily"}

        String studentName = jsonObject.getString("studentName");
        Integer studentAge = jsonObject.getInteger("studentAge");

        Student student1 = new Student(studentName, studentAge);//Student(studentName=lily, studentAge=12)

        //第二种方式,使用TypeReference<T>类,由于其构造方法使用protected进行修饰,故创建其子类
        Student student2 = JSONObject.parseObject(JSON_OBJ_STR, new TypeReference<Student>() {});//Student(studentName=lily, studentAge=12)

        //第三种方式,使用 Gson 的思想
        Student student3 = JSONObject.parseObject(JSON_OBJ_STR, Student.class);//Student(studentName=lily, studentAge=12)

        System.out.println(student1);
        System.out.println(student2);
        System.out.println(student3);
    }

    /**
     * JavaBean 到 json字符串-简单对象 的转换
     */
    @Test
    public void testJavaBeanObjToJSONStr() {

        Student student = new Student("lily", 12);
        System.out.println(student);//Student(studentName=lily, studentAge=12)
        String jsonString = JSONObject.toJSONString(student);
        System.out.println(jsonString);//{"studentAge":12,"studentName":"lily"}
    }

3.2.2json字符串-数组类型 和 JavaBean 互转
   /**
     * json字符串-数组类型 到 JavaBean_List 的转换
     */
    @Test
    public void testJSONStrToJavaBeanList() {

        //第一种方式
        JSONArray jsonArray = JSONArray.parseArray(JSON_ARRAY_STR);

        //遍历JSONArray
        List<Student> students = new ArrayList<Student>();
        Student student = null;
        for (Object object : jsonArray) {

            JSONObject jsonObjectone = (JSONObject) object;
            String studentName = jsonObjectone.getString("studentName");
            Integer studentAge = jsonObjectone.getInteger("studentAge");

            student = new Student(studentName,studentAge);
            students.add(student);
        }

        // students:  [Student(studentName=lily, studentAge=12), Student(studentName=lucy, studentAge=15)]
        System.out.println("students:  " + students);


        //第二种方式,使用TypeReference<T>类,由于其构造方法使用protected进行修饰,故创建其子类
        List<Student> studentList = JSONArray.parseObject(JSON_ARRAY_STR, new TypeReference<ArrayList<Student>>() {});
        //studentList:  [Student(studentName=lily, studentAge=12), Student(studentName=lucy, studentAge=15)]
        System.out.println("studentList:  " + studentList);

        //第三种方式,使用Gson的思想
        List<Student> studentList1 = JSONArray.parseArray(JSON_ARRAY_STR, Student.class);
        //studentList1:  [Student(studentName=lily, studentAge=12), Student(studentName=lucy, studentAge=15)]
        System.out.println("studentList1:  " + studentList1);

    }

    /**
     * JavaBean_List 到 json字符串-数组类型 的转换
     */
    @Test
    public void testJavaBeanListToJSONStr() {

        Student student = new Student("lily", 12);
        Student studenttwo = new Student("lucy", 15);

        List<Student> students = new ArrayList<Student>();
        students.add(student);
        students.add(studenttwo);
        //[Student(studentName=lily, studentAge=12), Student(studentName=lucy, studentAge=15)]
        System.out.println(students);

        String jsonString = JSONArray.toJSONString(students);
        //[{"studentAge":12,"studentName":"lily"},{"studentAge":15,"studentName":"lucy"}]
        System.out.println(jsonString);

    }


3.3json对象 和 javaBean 互转

3.3.1json对象 和 简单JavaBean 互转

    /**
     * 简单JavaBean_obj 到 json对象 的转换
     */
    @Test
    public void testJavaBeanToJSONObject(){

        //已知简单JavaBean_obj
        Student student = new Student("lily", 12);
        System.out.println(student);//Student(studentName=lily, studentAge=12)

        //方式一
        String jsonString = JSONObject.toJSONString(student);
        JSONObject jsonObject = JSONObject.parseObject(jsonString);
        System.out.println(jsonObject);//{"studentAge":12,"studentName":"lily"}

        //方式二
        JSONObject jsonObject1 = (JSONObject) JSONObject.toJSON(student);
        System.out.println(jsonObject1);//{"studentAge":12,"studentName":"lily"}
    }

    /**
     * 简单json对象 到 JavaBean_obj的转换
     */
    @Test
    public void testJSONObjectToJavaBean(){

        //已知简单json对象
        JSONObject jsonObject = JSONObject.parseObject(JSON_OBJ_STR);

        //第一种方式,使用TypeReference<T>类,由于其构造方法使用protected进行修饰,故创建其子类
        Student student = JSONObject.parseObject(jsonObject.toJSONString(), new TypeReference<Student>() {});
        System.out.println(student);//Student(studentName=lily, studentAge=12)

        //第二种方式,使用Gson的思想
        Student student1 = JSONObject.parseObject(jsonObject.toJSONString(), Student.class);
        System.out.println(student1);//Student(studentName=lily, studentAge=12)
    }

3.3.2JsonArray 和 JavaList 互转

    /**
     * JavaList 到 JsonArray 的转换
     */
    @Test
    public void testJavaListToJsonArray() {

        //已知JavaList
        Student student = new Student("lily", 12);
        Student studenttwo = new Student("lucy", 15);

        List<Student> students = new ArrayList<Student>();
        students.add(student);
        students.add(studenttwo);
        //[{"studentAge":12,"studentName":"lily"},{"studentAge":15,"studentName":"lucy"}]
        System.out.println(students);

        //方式一
        String jsonString = JSONArray.toJSONString(students);
        JSONArray jsonArray = JSONArray.parseArray(jsonString);
        //[Student(studentName=lily, studentAge=12), Student(studentName=lucy, studentAge=15)]
        System.out.println(jsonArray);

        //方式二
        JSONArray jsonArray1 = (JSONArray) JSONArray.toJSON(students);
        //[Student(studentName=lily, studentAge=12), Student(studentName=lucy, studentAge=15)]
        System.out.println(jsonArray1);
    }

    /**
     * JsonArray 到 JavaList 的转换
     */
    @Test
    public void testJsonArrayToJavaList() {

        //已知JsonArray
        JSONArray jsonArray = JSONArray.parseArray(JSON_ARRAY_STR);
        //[{"studentAge":12,"studentName":"lily"},{"studentAge":15,"studentName":"lucy"}]
        System.out.println(jsonArray);

        //第一种方式,使用TypeReference<T>类,由于其构造方法使用protected进行修饰,故创建其子类
        ArrayList<Student> students = JSONArray.parseObject(jsonArray.toJSONString(),
                new TypeReference<ArrayList<Student>>() {});
        //[Student(studentName=lily, studentAge=12), Student(studentName=lucy, studentAge=15)]
        System.out.println(students);

        //第二种方式,使用Gson的思想
        List<Student> students1 = JSONArray.parseArray(jsonArray.toJSONString(), Student.class);
        //[Student(studentName=lily, studentAge=12), Student(studentName=lucy, studentAge=15)]
        System.out.println(students1);
    }

3.3.3Json对象 和 复杂JavaBean 互转
  /**
     * 复杂JavaBean_obj 到 json对象 的转换
     */
    @Test
    public void testComplexJavaBeanToJSONObject() {

        //已知复杂JavaBean_obj
        Student student = new Student("lily", 12);
        Student studenttwo = new Student("lucy", 15);

        List<Student> students = new ArrayList<Student>();
        students.add(student);
        students.add(studenttwo);
        Course course = new Course("english", 1270);

        Teacher teacher = new Teacher("crystall", 27, course, (ArrayList<Student>) students);
        /*
        Teacher(teacherName=crystall, teacherAge=27, course=Course(courseName=english, code=1270),
         students=[Student(studentName=lily, studentAge=12), Student(studentName=lucy, studentAge=15)])
         */
        System.out.println(teacher);

        //方式一
        String jsonString = JSONObject.toJSONString(teacher);
        JSONObject jsonObject = JSONObject.parseObject(jsonString);
        /*
        {"teacherAge":27,"teacherName":"crystall","course":{"courseName":"english","code":1270},
        "students":[{"studentAge":12,"studentName":"lily"},{"studentAge":15,"studentName":"lucy"}]}
         */
        System.out.println(jsonObject);

        //方式二
        JSONObject jsonObject1 = (JSONObject) JSONObject.toJSON(teacher);
        /*
        {"teacherAge":27,"teacherName":"crystall","course":{"courseName":"english","code":1270},
        "students":[{"studentAge":12,"studentName":"lily"},{"studentAge":15,"studentName":"lucy"}]}
         */
        System.out.println(jsonObject1);

    }

    /**
     * 复杂json对象到JavaBean_obj的转换
     */
    @Test
    public void testComplexJSONObjectToJavaBean() {

        //已知复杂json对象
        JSONObject jsonObject = JSONObject.parseObject(COMPLEX_JSON_STR);

        //第一种方式,使用TypeReference<T>类,由于其构造方法使用protected进行修饰,故创建其子类
        Teacher teacher = JSONObject.parseObject(jsonObject.toJSONString(), new TypeReference<Teacher>() {});
        /*
        Teacher(teacherName=crystall, teacherAge=27, course=Course(courseName=english, code=1270),
        students=[Student(studentName=lily, studentAge=12), Student(studentName=lucy, studentAge=15)])
         */
        System.out.println(teacher);

        //第二种方式,使用Gson的思想
        Teacher teacher1 = JSONObject.parseObject(jsonObject.toJSONString(), Teacher.class);
        /*
        Teacher(teacherName=crystall, teacherAge=27, course=Course(courseName=english, code=1270),
        students=[Student(studentName=lily, studentAge=12), Student(studentName=lucy, studentAge=15)])
         */
        System.out.println(teacher1);
    }

3.3.4Json对象(JSONObject) 和 Map 互转
 
    @Test
    public void testMapToJSONObject() throws JsonProcessingException {
        HashMap<String, Object> map1 = new HashMap<>();
        map1.put("n",3);
        map1.put("samples",30);
        int [][] arr=new int[][]{{-3,-2,-1},{4,5,6}};
        map1.put("bound",arr);
        map1.put("population",60);
        map1.put("iterations",60);
        System.out.println(map1);//{bound=[[I@4629104a, n=3, samples=30, iterations=60, population=60}
        HashMap<String, Object> map = new HashMap<>();

        map.put("params",map1);
        System.out.println(map);//{params={bound=[[I@4629104a, n=3, samples=30, iterations=60, population=60}}

        //方法一:
        // 将 map 转换成 JSONObject
        //map 转 String
        ObjectMapper mapper = new ObjectMapper();
        String writeValueAsString = mapper.writeValueAsString(map);
        //string 转 JSONObject
        JSONObject jsonObject = JSONObject.parseObject(writeValueAsString);
        System.out.println(jsonObject);//{"params":{"bound":[[-3,-2,-1],[4,5,6]],"n":3,"samples":30,"iterations":60,"population":60}}


        //方法二:
        System.out.println("=======");
        // 将 map 转换成 JSONObject
        //JSON.toJSONString(map) 将 map 转为 json字符串
        JSONObject jsonObject1 = JSONObject.parseObject(JSON.toJSONString(map));
        System.out.println(jsonObject1);//{"params":{"bound":[[-3,-2,-1],[4,5,6]],"n":3,"samples":30,"iterations":60,"population":60}}

        // 将 JSONObject 转换成 map
        Map map2 = JSONObject.toJavaObject(jsonObject1, Map.class);//{"params":{"bound":[[-3,-2,-1],[4,5,6]],"n":3,"samples":30,"iterations":60,"population":60}}
        Map map3 = JSONObject.parseObject(jsonObject1.toJSONString());//{"params":{"bound":[[-3,-2,-1],[4,5,6]],"n":3,"samples":30,"iterations":60,"population":60}}
        System.out.println(map2);
        System.out.println(map3);

        System.out.println("========");


        Iterator<Map.Entry<String, Object>> iterator = jsonObject.entrySet().iterator();
        while (iterator.hasNext()){
            Map.Entry<String, Object> entry = iterator.next();
            System.out.println(entry.getKey());//params
            System.out.println(entry.getValue());//{"bound":[[-3,-2,-1],[4,5,6]],"n":3,"samples":30,"iterations":60,"population":60}
        }

    }
  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值