java 访问网址并将返回结果的json数组转换为List<String>

首先导入依赖

        <dependency>
            <groupId>com.alibabagroupId>
            <artifactId>fastjsonartifactId>
            <version>1.1.24version>
        dependency>

要返回的数据为

{
"code": 200,
"msg": "success",
"newslist": [{
	"news": [{}],
	"desc": {},
	"riskarea": {
		"mid": ["上海市上海市黄浦区打浦桥街道顺昌路612弄20号", "上海市上海市嘉定区马陆镇康年路261号工地宿舍""],
		"high": ["北京市朝阳区南磨房(地区)乡南新园社区", "北京市朝阳区十八里店(地区)乡周家庄中路19号院", "北京市房山区窦店镇于庄村"]
	}
}]

}

 		//要访问的网址
 		 String url=String.format("http://api.tianapi.com/ncov/index?key=d334721cf6eba2d619a5855420ec352c");
        StringBuffer json=new StringBuffer();

        try {
            URL u=new URL(url);
            URLConnection yc=u.openConnection();

//            读取返回数据
            BufferedReader in=new BufferedReader(new InputStreamReader(yc.getInputStream(),"UTF-8"));
            String inputline = null;

            while((inputline=in.readLine())!=null){
                json.append(inputline);
            }
            in.close();
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

//        获得jsonObject
        JSONObject jo=JSON.parseObject(json.toString());
        com.alibaba.fastjson.JSONArray newslist = jo.getJSONArray("newslist");

        List<String> list=new ArrayList<>();
        for(int i=0;i<newslist.size();i++) {
            JSONObject riskarea=newslist.getJSONObject(i).getJSONObject("riskarea");
            com.alibaba.fastjson.JSONArray mid=riskarea.getJSONArray("high");

            for(int j=0;j<mid.size();j++) {
                list.add(mid.getString(j));
            }
        }

        return list;

你可能感兴趣的:(java,json,开发语言)