JAVA 爬虫 获取json格式的数据并生成javaBean

  一、写在最前

    这是我第一篇非作业的博客,这一切都是因为该死的java爬虫,我在爬取json数据是感受到了深深的恶意,而这恶意来源也非常清楚——python用起来简单。

    所以我把问题解决了立马想到要写一篇帖子记录下这个弄了一下午的问题。

    对了,同时提醒自己在最近把序列化,反射机制再过一遍,快忘完了!!!

  二、使用fastjson 解决

    这是目标请求:http://www.nmc.cn/f/rest/province

    他返回了json格式的数据,接下来获取这些json格式的数据,放在一个实体类中

    

    1.首先是这个JavaBean的代码 它只有一层 对于多层的这里有一篇博文明天看https://blog.csdn.net/a_rookie_xiaoming/article/details/52165502

package com.test;

public class Province {
    private String code;
    private String name;
    private String url;
    
    public Province(){}
    
    public Province(String code, String name, String url){
        this.code = code;
        this.name = name;
        this.url = url;
    }

    public String getCode() {
        return code;
    }

    public void setCode(String code) {
        this.code = code;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getUrl() {
        return url;
    }

    public void setUrl(String url) {
        this.url = url;
    }
}

   2.然后先获得这个请求返回的数据:

  

package com.test;

import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

public class getEntity {
    public static String get(){
        //创建客户端
        CloseableHttpClient httpClient = HttpClients.createDefault();
        
        String entityr = "";
        //创建Get实例
        HttpGet httpGet = new HttpGet("http://www.nmc.cn/f/rest/province");
        
        //添加请求头的信息,模拟浏览器访问
        httpGet.addHeader("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/71.0.3573.0 Safari/537.36");

        try{
            //获得Response
            CloseableHttpResponse response = httpClient.execute(httpGet);
            
            if(response.getStatusLine().getStatusCode() == 200){
                //当响应状态码为200时,获得该网页源码并打印 
                String entity = EntityUtils.toString(response.getEntity(),"utf-8");
                entityr = entity;
            }
            
        }catch(Exception e){
            e.printStackTrace();
        }
        return entityr;
    }

}

    3.弄到实体类里面大功告成:

package com.test;

import java.util.List;
import com.alibaba.fastjson.JSON;


public class Demo {

    public static void main(String[] args) {
        //获得响应的ajax,json格式的String
        String str = getEntity.get();
    
        //字符串序列化成集合
        List<Province> list= JSON.parseArray(str,Province.class);
        for(Province item: list){
            System.out.println(item.getCode());
            System.out.println(item.getName());
            System.out.println(item.getUrl());
        }    
    }
}

    结果:

    三、最后

    明天再看看有没有更好更高效的解决方法

posted @ 2018-11-17 23:24  Weeeeew  阅读(3941)  评论(0编辑  收藏  举报