美文网首页
Java Jackson读取Json以及使用Bean生成Json

Java Jackson读取Json以及使用Bean生成Json

作者: 从不看女主播的韩超 | 来源:发表于2018-04-18 20:23 被阅读0次

    一.环境配置

    JavaSE版本:1.8
    Maven配置如下:

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <jackson-version>2.8.1</jackson-version>
    </properties>
    
    <dependencies>
        <dependency>
          <groupId>junit</groupId>
          <artifactId>junit</artifactId>
          <version>3.8.1</version>
          <scope>test</scope>
       </dependency>
       <!--Jackson required包-->
       <dependency>
          <groupId>com.fasterxml.jackson.core</groupId>
          <artifactId>jackson-core</artifactId>
          <version>${jackson-version}</version>
       </dependency>
       <dependency>
          <groupId>com.fasterxml.jackson.core</groupId>
          <artifactId>jackson-databind</artifactId>
          <version>${jackson-version}</version>
       </dependency>
       <dependency>
          <groupId>com.fasterxml.jackson.core</groupId>
          <artifactId>jackson-annotations</artifactId>
          <version>${jackson-version}</version>
       </dependency>
    </dependencies>
    

    解析JSON

    要解析的JSON数据如下:

    {
        name:"韩超",
        age:18,
        code:1507030123,
        hobbies:["football","game","baskerball"]
        details:
        {
            birthday:869760000,
            extar:[1321,"hahaha","zzz421"]
        }
    }
    

    解析示例代码

    @Test
    public void testParseJson() {
        //原数据
        String data="{" + 
                "   \"name\":\"韩超\"," + 
                "   \"age\":18," + 
                "   \"code\":1507030123," + 
                "   \"hobbies\":[\"football\",\"game\",\"baskerball\"]," + 
                "   \"details\":" + 
                "   {" + 
                "       \"birthday\":869760000," + 
                "       \"extar\":[1321,\"hahaha\",\"zzz421\"]" + 
                "   }" + 
                "}";
        //创建一个ObjectMapper对象
        ObjectMapper objectMapper=new ObjectMapper();
        //读取json数据,返回一个JsonNode对象指向根节点
        try {
            JsonNode jsonNode=objectMapper.readTree(data);
            //利用JsonNode的path方法获取子节点,path方法的返回值也是JsonNode
            JsonNode subNode=jsonNode.path("details");//得到details节点
            //JsonNode对象的asInt(),asText()等方法用于获取值
            
            System.out.println(jsonNode.path("name").asText());//返回字符串,韩超
            System.out.println(jsonNode.path("age").asInt());//返回整形数据,18
            System.out.println(jsonNode.path("code").asLong());//返回长整型数据,1507030123
            
            //对于数组,可以使用size方法获取数组长度,get(index)获取索取为index的值
            for(int i=0;i<jsonNode.path("hobbies").size();i++)
                System.out.println(jsonNode.path("hobbies").get(i).asText());//输出hobbies对应的数组
            
            //获取details.birthday
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd-HH-mm");  
            sdf.setTimeZone(TimeZone.getTimeZone("GMT+8"));
            System.out.println(sdf.format(new Date(subNode.path("birthday").asLong()*1000)));
            
            for(int i=0;i<subNode.path("extar").size();i++)
                System.out.println(subNode.path("extar").get(i).asText());//输出details.extar对应的数组
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }   
    }
    

    JavaBean转换成JSON

    Bean示例

    public class MyBean implements Serializable{
        private String name;
        private Integer age;
        private Long code;
        private String[] hobbies;
        private Map<String,Object> details;
        public String getName() {
            return name;
        }
        public void setName(String name) {
            this.name = name;
        }
        public Integer getAge() {
            return age;
        }
        public void setAge(Integer age) {
            this.age = age;
        }
        public Long getCode() {
            return code;
        }
        public void setCode(Long code) {
            this.code = code;
        }
        public String[] getHobbies() {
            return hobbies;
        }
        public void setHobbies(String[] hobbies) {
            this.hobbies = hobbies;
        }
        public Map<String, Object> getDetails() {
            return details;
        }
        public void setDetails(Map<String, Object> details) {
            this.details = details;
        }
    }
    

    生成JSON代码示例

    @Test
    public void testJsonBuilder() {
        //写入数据
        MyBean myBean=new MyBean();
        myBean.setAge(18);
        myBean.setName("韩超");
        String[] hobbies= {"game","it"};
        Object[] extra= {"1212",233,"haha","hdfa31"};
        Map<String, Object> map=new HashMap<String, Object>();
        map.put("birthday",869760000);
        map.put("extra", extra);
        myBean.setDetails(map);
        
        ObjectMapper objectMapper=new ObjectMapper();
        try {
            //利用writeValueAsString方法将一个Bean转换成Json数据
            System.out.println(objectMapper.writeValueAsString(myBean));
            //如果要生成json数组,只需使用List对象存储一个个Bean就行了
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }
    }
    

    输出结果

    相关文章

      网友评论

          本文标题:Java Jackson读取Json以及使用Bean生成Json

          本文链接:https://www.haomeiwen.com/subject/bcsbkftx.html