Java转JSON

  • 从Java对象转换
  • 从JsonNode Tree
  • 构建JSON Stream

从java对象

ObjectMapper mapper = new ObjectMapper();
String result = mapper.writeValueAsString(object);

从JsonNode

// Create the node factory that gives us nodes.
JsonNodeFactory factory = new JsonNodeFactory(false);

// create a json factory to write the treenode as json. for the example
// we just write to console
JsonFactory jsonFactory = new JsonFactory();
JsonGenerator generator = jsonFactory.createGenerator(System.out);
ObjectMapper mapper = new ObjectMapper();

// the root node - album
JsonNode album = factory.objectNode();
mapper.writeTree(generator, album);

从JSON Stream

JsonFactory factory = new JsonFactory();
JsonGenerator generator = factory.createGenerator(new FileWriter(new File("albums.json")));

// start writing with {
generator.writeStartObject();
generator.writeFieldName("title");
generator.writeString("Free Music Archive - Albums");
generator.writeFieldName("dataset");
// start an array
generator.writeStartArray();
generator.writeStartObject();
generator.writeStringField("album_title", "A.B.A.Y.A.M");
generator.writeEndObject();
generator.writeEndArray();
generator.writeEndObject();

generator.close();

JSON转Java

  • Streaming - 使用JsonParser解析JSON stream. 它提供JSON elements作为tokens. 使用JsonGenerator产生JSON字符串
  • Tree Traversing - JSON可以被读进一个JsonNode中, 然后可以通过遍历来找到对应的属性
  • Data Binding - 从JSON字符串构建Java对象

通过Streaming

// Get a list of albums from free music archive. limit the results to 5
        String url = "http://freemusicarchive.org/api/get/albums.json?api_key=60BLHNQCAOUFPIBZ&limit=5";
        // get an instance of the json parser from the json factory
        JsonFactory factory = new JsonFactory();
        JsonParser parser = factory.createParser(new URL(url));
 
        // continue parsing the token till the end of input is reached
        while (!parser.isClosed()) {
            // get the token
            JsonToken token = parser.nextToken();
            // if its the last token then we are done
            if (token == null)
                break;
            // we want to look for a field that says dataset
 
            if (JsonToken.FIELD_NAME.equals(token) && "dataset".equals(parser.getCurrentName())) {
                // we are entering the datasets now. The first token should be
                // start of array
                token = parser.nextToken();
                if (!JsonToken.START_ARRAY.equals(token)) {
                    // bail out
                    break;
                }
                // each element of the array is an album so the next token
                // should be {
                token = parser.nextToken();
                if (!JsonToken.START_OBJECT.equals(token)) {
                    break;
                }
                // we are now looking for a field that says "album_title". We
                // continue looking till we find all such fields. This is
                // probably not a best way to parse this json, but this will
                // suffice for this example.
                while (true) {
                    token = parser.nextToken();
                    if (token == null)
                        break;
                    if (JsonToken.FIELD_NAME.equals(token) && "album_title".equals(parser.getCurrentName())) {
                        token = parser.nextToken();
                        System.out.println(parser.getText());
                    }
 
                }
 
            }
 
        }
 
    }

通过JsonNode
Jackson通过com.fasterxml.jackson.databind.JsonNode提供一个树形的node, 类似XML DOM树中的node.

// create an ObjectMapper instance.
        ObjectMapper mapper = new ObjectMapper();
        // use the ObjectMapper to read the json string and create a tree
        JsonNode node = mapper.readTree(genreJson);
 
        // lets see what type the node is
        System.out.println(node.getNodeType()); // prints OBJECT
        // is it a container
        System.out.println(node.isContainerNode()); // prints true
        // lets find out what fields it has
        Iterator<String> fieldNames = node.fieldNames();
        while (fieldNames.hasNext()) {
            String fieldName = fieldNames.next();
            System.out.println(fieldName);// prints title, message, errors,
                                            // total,
                                            // total_pages, page, limit, dataset
        }

通过Data Binding

String url = "http://freemusicarchive.org/api/get/albums.json?api_key=60BLHNQCAOUFPIBZ&limit=2";
        ObjectMapper mapper = new ObjectMapper();
        mapper.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES);
        Albums albums = mapper.readValue(new URL(url), Albums.class);

对于简单类型的List和Map, Jackson可以直接转换

Map<String, Integer> scoreByName = mapper.readValue(jsonSource, Map.class);
List<String> names = mapper.readValue(jsonSource, List.class);

但是对于POJO类型的List和Map需要指定具体类型

Map<String, ResultValue> results = mapper.readValue(jsonSource,
   new TypeReference<Map<String, ResultValue>>() { } );

http://www.studytrails.com/java/json/java-jackson-json-tree-parsing/
https://github.com/FasterXML/jackson-databind

posted on 2018-12-28 22:15  浮舟z  阅读(256)  评论(0编辑  收藏  举报