首页 > 编程语言 >JSON_解析器Jackson_java对象转json_注解与JSON_解析器Jackson_java对象转json_List&Map

JSON_解析器Jackson_java对象转json_注解与JSON_解析器Jackson_java对象转json_List&Map

时间:2023-02-24 14:47:21浏览次数:38  
标签:解析器 java 23 张三 Person json new

JSON_解析器Jackson_java对象转json_注解

      

    1. 注解:


      1. @JsonIgnore:排除属性。

 

 

 

 


      2. @JsonFormat:属性值得格式化
        @JsonFormat(pattern = "yyyy-MM-dd")

 

 

 

 

 

 

 

 

 

JSON_解析器Jackson_java对象转json_List&Map

  1. 复杂java对象转换
    1. List:数组

  @Test
    public void test3() throws Exception {
        //1.创建Person对象
        Person p = new Person();
        p.setName("张三");
        p.setAge(23);
        p.setGender("男");
        p.setBirthday(new Date());

        Person p1 = new Person();
        p1.setName("张三");
        p1.setAge(23);
        p1.setGender("男");
        p1.setBirthday(new Date());

        Person p2 = new Person();
        p2.setName("张三");
        p2.setAge(23);
        p2.setGender("男");
        p2.setBirthday(new Date());


        //创建List集合
        List<Person> ps = new ArrayList<Person>();
        ps.add(p);
        ps.add(p1);
        ps.add(p2);


        //2.转换
        ObjectMapper mapper = new ObjectMapper();
        String json = mapper.writeValueAsString(ps);
        // [{},{},{}]
        //[{"name":"张三","age":23,"gender":"男","birthday":"2018-07-07"},{"name":"张三","age":23,"gender":"男","birthday":"2018-07-07"},{"name":"张三","age":23,"gender":"男","birthday":"2018-07-07"}]
        System.out.println(json);
    }

 

 

    2. Map:对象格式一致

@Test
    public void test4() throws Exception {
        //1.创建map对象
        Map<String,Object> map = new HashMap<String,Object>();
        map.put("name","张三");
        map.put("age",23);
        map.put("gender","男");


        //2.转换
        ObjectMapper mapper = new ObjectMapper();
        String json = mapper.writeValueAsString(map);
        //{"name":"张三","age":23,"gender":"男"}
        System.out.println(json);//{"gender":"男","name":"张三","age":23}
    }

 

 

 

翻译

搜索

复制

标签:解析器,java,23,张三,Person,json,new
From: https://www.cnblogs.com/x3449/p/17151381.html

相关文章