Advertisement
FancyKing

第2关:获取携程网北京市的所有酒店信息

Apr 3rd, 2020
181
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 2.11 KB | None | 0 0
  1. package step2;
  2. import java.util.ArrayList;
  3. import java.util.HashMap;
  4. import java.util.List;
  5. import com.alibaba.fastjson.JSON;
  6. import com.alibaba.fastjson.JSONArray;
  7. import com.alibaba.fastjson.JSONObject;
  8. import java.io.*;
  9. public class Task {
  10.    
  11.     /**
  12.      * 使用fastjson解析数据
  13.      * @param hotelResult   已经为你解析的所需json数据
  14.      * @return
  15.      */
  16.     public List<Hotel> getHotle(String hotelResult){
  17.         /**********   Begin   **********/
  18.        
  19.         List<Hotel> a = new ArrayList<Hotel>();
  20.         JSONObject b = JSONObject.parseObject(hotelResult);
  21.         List<Hotel> c = JSON.parseArray(b.getString("hotelPositionJSON"), Hotel.class);
  22.  
  23.         JSONArray hotelsPrice = b.getJSONArray("htllist");
  24.         if (hotelsPrice != null && !hotelsPrice.isEmpty()) {
  25.             for (int i = 0; i < c.size(); i++) {
  26.                 JSONObject priceObj = hotelsPrice.getJSONObject(i);
  27.                 if (priceObj != null && !priceObj.isEmpty()) {
  28.                     Hotel hotel = c.get(i);
  29.                     String hotelId = priceObj.getString("hotelid");
  30.                     double price = priceObj.getDoubleValue("amount");
  31.                     if (hotel.getId().equals(hotelId)) {
  32.                         hotel.setPrice(price);
  33.                     }
  34.                 }
  35.             }
  36.         }
  37.         a.addAll(c);
  38.         return a;
  39.         /**********   End   **********/
  40.     }
  41.  
  42.  
  43.  
  44.     /**
  45.      * 由于携程网站经常更新,为了不影响测试,我们直接读取本地文件。
  46.      * @return
  47.      */
  48.     public  String getHotelListString(String cityId,String url){
  49.         String hotelResult="";
  50.         try {
  51.             InputStream is = new FileInputStream(new File("src/step2/hotelResult.txt"));
  52.             byte[] b=new byte[1024];
  53.             int len=0;
  54.             try {
  55.                 while((len=is.read(b))!=-1){
  56.                     String str=new String(b,0,len);
  57.                     hotelResult+=str;
  58.                 }
  59.             } catch (IOException e) {
  60.                 e.printStackTrace();
  61.             }
  62.         } catch (FileNotFoundException e) {
  63.             e.printStackTrace();
  64.         }
  65.        
  66.         return hotelResult;
  67.     }
  68.  
  69. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement