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"));
        }
 
    }

项目源码免费获取 个人博客,百度网盘地址+提取码,文件无密~

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值