ネットワークのjsonファイルGson解析jsonファイルを取得

3466 ワード

詳細
/**
	 *      json  
	 * @param url
	 * @return
	 * @throws ClientProtocolException
	 * @throws IOException
	 */
	public static String getJSONData(String url)
			throws ClientProtocolException, IOException {
		String result = "";
		URL url2 = null;
		try {
			url2 = new URL(url);
		} catch (MalformedURLException e) {
			System.out.println("getJSONData" + "MalformedURLException");
		}
		if (url2 != null) {
			try {
				//   HttpURLConnection    
				HttpURLConnection urlConn = (HttpURLConnection) url2
						.openConnection();
				urlConn.setRequestProperty("Accept-Encoding", "gzip,deflate");
				urlConn.connect();
				String str = urlConn.getContentEncoding();
				InputStream is;
				if (str != null) {
					if (str.equalsIgnoreCase("gzip")) {
						is = new GZIPInputStream(urlConn.getInputStream());
					} else {
						is = urlConn.getInputStream();
					}

				} else {
					is = urlConn.getInputStream();
				}
				//        
				InputStreamReader in = new InputStreamReader(is, "UTF-8");
				//      BufferReader
				BufferedReader buffer = new BufferedReader(in);
				String inputLine = null;
				//             
				while ((inputLine = buffer.readLine()) != null) {
					//          
result += inputLine + "
"; } // InputStreamReader in.close(); // http urlConn.disconnect(); } catch (Exception e) { e.printStackTrace(); } } return result; }

 
	/**
	  * 
	  * @param path      
	  */
	 public static void isExist(String path) {
	  File file = new File(path);
	    //         ,           
	  if (!file.exists()) {
	   file.mkdir(); 
	   System.out.println("----       .");
	  }else{
		  System.out.println("----     .");
	  }
	  
	 }

 
 
jsonファイルフォーマット:
{"page":1,"results":[{"adult":false,"backdrop_path":"/a K dfFihGoCCUokcR 5 ZeotwzFW 5 g.jpg","id":202220,"original_title":"不二神探","release_date":"2013-12-31","poster_path":":""/bXd 9 v 2 fSVZih 0 frr 2 kv 2 Mt 1 LBHq.jpg","popularity":1.4432552525252522125522125522121255221 613959,『title』:『不二神探』,『vote_average』:2.5,『vote_count』:14},『total_pages』:1,『total_results』:1}
 
	/**
	 * @param args
	 */
	public static void main(String[] args) {
		 Gson gson = new Gson();
		try {
            String jsonUrl = getJSONData(path);
            VideoInfo info = gson.fromJson(jsonUrl, VideoInfo.class);
                    int len = info.getResults().size();           
                    for(int i=0; i 
  

 

    gson jar

 

 

  • gson-2.2.4.jar (186 KB)
  • ダウンロード回数:0
  • gson-2.2.4-javadoc.jar (243.5 KB)
  • ダウンロード回数:0
  • gson-2.2.4-sources.jar (124.6 KB)
  • ダウンロード回数:0