带你五分钟搞定Jackson JSON Processor

传送门 ☞ 轮子的专栏 ☞ 转载请注明 ☞ http://blog.csdn.net/leverage_1229

1Jackson 是什么?

(1)崇尚速度的(传说比其他Java json parser和data binder执行起来更快)
(2)数据流动的(读取,写入)
(3)完全独立的(独立于JDK之外的其他包)
(4)火力十足的(为通用JDK类提供完整的数据绑定,就像Java bean class, Collection, Map or Enum),可配置的
(5)开放源代码的(Apache License – or, until 2.1, alternatively LGPL)
        Jackson就是这样一个具有上述五大特性的JSON处理器。它提供JSON解析与JSON构建作为基础构造块,另有一个功能强大的数据绑定器(支持JSON与POJO相互转换)和树型结构作为可选附加块。
        也就是说,你可以通过调用流式API、POJO数据绑定、树型结构三种方式来生成和解析JSON。

2JSON三种方式

(1)流式API:读取和写入JSON内容视作离散事件。
org.codehaus.jackson.JsonParser reads
org.codehaus.jackson.JsonGenerator writes
(2)树型:提供一个JSON文档的可变内存树的表示形式。
org.codehaus.jackson.map.ObjectMapper 生成树;该树由JsonNode节点组成
树型类似于XML DOM
(3)数据绑定:提供基于属性访问器规约或注解的JSON和POJO相互转换。
有两种形式:简单数据绑定和完整数据绑定:
简单数据绑定:从Java Map、List、String、Numbers、Boolean和空值进行转换
完整数据绑定:从任何Java bean类型(以及“简单”类型)进行转换
org.codehaus.jackson.map.ObjectMapper 对这两种形式进行编组处理(写入 JSON)和逆向编组(读取 JSON)
(4)使用特点
性能最好的是流式API,另外两种方式都是基于它实现的;使用最方便的是数据绑定;最灵活的是树型。

3示例

3.1工程包目录


3.2完整数据绑定(POJO)

(1)Json字符串:data.json
{
   "name" : { "first" : "Joe", "last" : "Sixpack" },
   "gender" : "MALE",
   "verified" : false,
   "userImage" : "Rm9vYmFyIQ=="
}
(2)Json转换成实体类:json2Entity()
    /**
     * 将Json字符串转换成实体类
     */
    public static void json2Entity() {
        try {
            User user = mapper.readValue(new File("src/com/roctec/json/data.json"), User.class);
            System.out.println(user);
        } catch (JsonParseException e) {
            e.printStackTrace();
        } catch (JsonMappingException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
(3)实体类:User.java
package com.roctec.entity;

import java.util.Arrays;

public class User {
    public enum Gender {
        MALE, FEMALE
    };

    public static class Name {
        private String _first, _last;

        public String getFirst() {
            return _first;
        }

        public String getLast() {
            return _last;
        }

        public void setFirst(String s) {
            _first = s;
        }

        public void setLast(String s) {
            _last = s;
        }
    }

    private Gender _gender;
    private Name _name;
    private boolean _isVerified;
    private byte[] _userImage;

    public Name getName() {
        return _name;
    }

    public boolean isVerified() {
        return _isVerified;
    }

    public Gender getGender() {
        return _gender;
    }

    public byte[] getUserImage() {
        return _userImage;
    }

    public void setName(Name n) {
        _name = n;
    }

    public void setVerified(boolean b) {
        _isVerified = b;
    }

    public void setGender(Gender g) {
        _gender = g;
    }

    public void setUserImage(byte[] b) {
        _userImage = b;
    }

    @Override
    public String toString() {
        return "User [_gender=" + _gender + ", _name=[_first=" + _name._first + ", _last=" + _name._last
                + "], _isVerified=" + _isVerified + ", _userImage="
                + Arrays.toString(_userImage) + "]";
    }
}
(4)实体类转换成Json:entity2Json()
   /**
     * 将实体类转换成Json字符串
     */
    public static void entity2Json() {
        User user = new User();
        User.Name name = new User.Name();
        name.setFirst("Joe");
        name.setLast("Sixpack");
        user.setName(name);
        user.setGender(User.Gender.MALE);
        user.setVerified(false);
        user.setUserImage("Rm9vYmFyIQ==".getBytes());
        try {
            mapper.writeValue(new File("src/com/roctec/json/entity.json"), user);
        } catch (JsonGenerationException e) {
            e.printStackTrace();
        } catch (JsonMappingException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

3.3简单数据绑定(Map)

(1)Json转换成Map:json2Map()
    /**
     * 将Json字符串转换成map
     */
    public static void json2Map() {
        try {
            @SuppressWarnings("unchecked")
            Map<String, Object> map = mapper.readValue(new File("src/com/roctec/json/data.json"), Map.class);
            for (Map.Entry<String, Object> entity : map.entrySet()) {
                System.out.println(entity.getKey() + "=" + entity.getValue());
            }
        } catch (JsonParseException e) {
            e.printStackTrace();
        } catch (JsonMappingException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
(2)Map转换成Json:map2Json()
    /**
     * 将map转换成Json字符串
     */
    public static void map2Json() {
        Map<String,Object> map = new HashMap<String,Object>();
        Map<String,String> name = new HashMap<String,String>();
        name.put("first", "Joe");
        name.put("last", "Sixpack");
        map.put("name", name);
        map.put("gender", "MALE");
        map.put("verified", Boolean.FALSE);
        map.put("userImage", "Rm9vYmFyIQ==");
        try {
            mapper.writeValue(new File("src/com/roctec/json/map.json"), map);
        } catch (JsonParseException e) {
            e.printStackTrace();
        } catch (JsonMappingException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

3.4树型绑定

(1)Json转换成树形:json2Tree()
    /**
     * 将Json字符串转换成树形
     */
    public static void json2Tree() {
        try {
            // 使用mapper.readTree(source),或使用mapper.readValue(source, JsonNode.class);
            JsonNode rootNode = mapper.readTree(new File("src/com/roctec/json/data.json"));
            // 确保"last name"不是"Xmler";如果是,就转换为"Jsoner"
            JsonNode nameNode = rootNode.path("name");
            String lastName = nameNode.path("last").getTextValue();
            if("xmler".equalsIgnoreCase(lastName)) {
                ((ObjectNode)nameNode).put("last", "Jsoner");
            }
            mapper.writeValue(new File("src/com/roctec/json/tree.json"), rootNode);
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } 
    }
(2)树形转换成Json:json2Tree()
    /**
     * 将树形转换成Json字符串
     */
    public static void tree2Json() {
        ObjectNode rootNode = mapper.createObjectNode();
        ObjectNode nameNode = rootNode.putObject("name");
        nameNode.put("first", "Joe");
        nameNode.put("last", "Sixpack");
        rootNode.put("gender", User.Gender.MALE.toString());
        rootNode.put("verified", false);
        byte[] imageBuf = "Rm9vYmFyIQ==".getBytes();
        rootNode.put("userImage", imageBuf);
        try {
            mapper.writeValue(new File("src/com/roctec/json/tree.json"), rootNode);
        } catch (JsonGenerationException e) {
            e.printStackTrace();
        } catch (JsonMappingException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

3.5流式API

(1)生成Json:generateJson()
    /**
     * 构造Json字符串
     */
    public static void generateJson() {
        try {
            JsonFactory factory = mapper.getJsonFactory();
            JsonGenerator generator = factory.createJsonGenerator(new File("src/com/roctec/json/write.json"), JsonEncoding.UTF8);
            generator.writeStartObject();
            generator.writeObjectFieldStart("name");
            generator.writeStringField("first", "Joe");
            generator.writeStringField("last", "Sixpack");
            generator.writeEndObject();
            generator.writeStringField("gender", User.Gender.MALE.toString());
            generator.writeBooleanField("verified", false);
            generator.writeFieldName("userImage");
            byte[] imageBuf = "Rm9vYmFyIQ==".getBytes();
            generator.writeBinary(imageBuf);
            generator.writeEndObject();
            generator.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
(2)解析Json:parseJson()
    /**
     * 解析Json字符串
     */
    public static void parseJson() {
        try {
            JsonFactory factory = mapper.getJsonFactory();
            JsonParser parser = factory.createJsonParser(new File("src/com/roctec/json/data.json"));
            User user = new User();
            parser.nextToken();
            while(parser.nextToken() != JsonToken.END_OBJECT) {
                String fieldName = parser.getCurrentName();
                parser.nextToken();
                if("name".equals(fieldName)) {
                    User.Name name = new User.Name();
                    while(parser.nextToken() != JsonToken.END_OBJECT) {
                        String nameField = parser.getCurrentName();
                        parser.nextToken();
                        if("first".equals(nameField)) {
                            name.setFirst(parser.getText());
                        } else if("last".equals(nameField)) {
                            name.setLast(parser.getText());
                        } else {
                            throw new IllegalStateException("Unrecognized field '" + fieldName + "'!");
                        }
                    }
                    user.setName(name);
                } else if("gender".equals(fieldName)) {
                    user.setGender(User.Gender.valueOf(parser.getText()));
                } else if("verified".equals(fieldName)) {
                    user.setVerified(parser.getCurrentToken() == JsonToken.VALUE_TRUE);
                } else if("userImage".equals(fieldName)) {
                    user.setUserImage(parser.getBinaryValue());
                } else {
                    throw new IllegalStateException("Unrecognized field '" + fieldName + "'!");
                }
            }
            parser.close();
            System.out.println(user);
        } catch (JsonParseException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
(3)解析Json数组:parseJsonArray()
    /**
     * 解析Json数组
     */
    public static void parseJsonArray() {
        String json = "[{\"foo\": \"bar\"}, {\"foo\": \"biz\"}]";
        try {
            JsonFactory factory = mapper.getJsonFactory();
            JsonParser parser = factory.createJsonParser(json);
            parser.nextToken();
            while(parser.nextToken() == JsonToken.START_OBJECT) {
                Foo foo = mapper.readValue(parser, Foo.class);
                System.out.println(foo);
            }
            parser.close();
        } catch (JsonParseException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
(4)实体类:Foo.java
package com.roctec.entity;

public class Foo {
    public String foo;

    public String getFoo() {
        return foo;
    }

    public void setFoo(String foo) {
        this.foo = foo;
    }

    @Override
    public String toString() {
        return "Foo [foo=" + foo + "]";
    }
    
}

        最后介绍一个窍门:可以通过JsonParser和JsonGenerator直接实现数据绑定和树型。请查看如下方法:
JsonParser.readValueAs()
JsonParser.readValueAsTree()
JsonGenerator.writeObject()
JsonGenerator.writeTree()
        注意一点,确保使用的org.codehaus.jackson.map.MappingJsonFactory是“适用数据绑定”的解析器和生成器实例(而非基本的org.codehaus.jackson.JsonFactory)。

posted @ 2013-08-08 23:47  Innosight  阅读(1318)  评论(0编辑  收藏  举报