Jackson:Java解析Json——树模型栗子

JSON to Java Tree Model Example

Jackson提供了一个TreeNode类: com.fasterxml.jackson.databind.JsonNode。ObjectMapper提供了一个方法将JSON转换为一个以JsonNode作为根节点的TreeNode。这和DOM 节点在XML DMO树中比较相似。下面的栗子展示了从JSON字符串构建一棵树的过程;

public static void main(String[] args) throws MalformedURLException, IOException {
        // 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=2";//译者注:实际上,这个URL无法访问,这里就不提供模拟数据啦,理解流程即可;
        // Get the contents of json as a string using commons IO IOUTils class.
        String genreJson = IOUtils.toString(new URL(url));
 
        // 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
        }
 
        // we now know what elemets the container has. lets get the value for
        // one of them
        System.out.println(node.get("title").asText()); // prints
                                                        // "Free Music Archive".
 
        // Lets look at the dataset now.
        JsonNode dataset = node.get("dataset");
 
        // what is its type?
        System.out.println(dataset.getNodeType()); // Prints ARRAY
 
        // so the dataset is an array. Lets iterate through the array and see
        // what each of the elements are
        Iterator<JsonNode> datasetElements = dataset.iterator();
        while (datasetElements.hasNext()) {
            JsonNode datasetElement = datasetElements.next();
            // what is its type
            System.out.println(datasetElement.getNodeType());// Prints Object
            // it is again a container . what are the elements ?
            Iterator<String> datasetElementFields = datasetElement.fieldNames();
            while (datasetElementFields.hasNext()) {
                String datasetElementField = datasetElementFields.next();
                System.out.println(datasetElementField); 
            }
            // break from the loop, since we just want to see the structure
            break;
        }
    }
// prints 
// album_id,
// album_title,
// album_handle,
// album_url,
// album_type,
// artist_name,
// artist_url,
// album_producer,
// album_engineer,
// album_information,
// album_date_released,
// album_comments,
// album_favorites,
// album_tracks,
// album_listens,
// album_date_created,
// album_image_file,
// album_images

让我们看看另外一个使用path方法的例子。path方法和get方法很类似,但是如果节点不存在,它不是返回null,而是返回一个类型为MissingNode的对象;

public static void main(String[] args) throws MalformedURLException, IOException {
        // 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=10";//译者注:同样,url也访问不了;
        // Get the contents of json as a string using commons IO IOUTils class.
        String genreJson = IOUtils.toString(new URL(url));
 
        // 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);
 
        // not the use of path. this does not cause the code to break if the
        // code does not exist
        Iterator<JsonNode> albums = node.path("dataset").iterator();
        while (albums.hasNext()) {
            System.out.println(albums.next().path("album_title"));
        }
 
    }

关注个人微信公众号:落花流水存心阁,不仅能免费获得相关项目的源码,还可以扩展思维,启迪智慧哦~
Jackson:Java解析Json——树模型栗子
后台回复:json。获得项目源码~

如果觉得文章写的不错,也可以小小地打赏一下嘛~ 注意,多余0.5元的打赏部分将原路径返回心意到就ok,精神鼓励远胜于物质鼓励~
也期待合作,“码”上改变~

微信账号 支付宝账号
Jackson:Java解析Json——树模型栗子 Jackson:Java解析Json——树模型栗子