2013-08-22 2 views
0

JSON 문자열/응답 및 간단한 구문 분석 및 개체/배열 가져올 필요가 있으므로 목록에서 목록을 가져올 필요가 실제로 실제로 어떻게 그것을 왜냐하면 많은 파서와 간단한 JSON-es를 사용하는 모든 예제가 있기는하지만 필자는 약간 어려워서 탐색해야하기 때문이다. 여기 내가 http://json-lib.sourceforge.net/ 같은 이것에 대한 라이브러리, 뭔가 사용하십시오구문 분석 JSON 문자열 java, 모범 사례

{ 
    "HotelListResponse": { 
     "customerSessionId": "0ABAAA83-04C7-5B91-40A2-754D7299476C", 
     "numberOfRoomsRequested": 1, 
     "moreResultsAvailable": true, 
     "cacheKey": "-4804c75b:140a754d729:4da2", 
     "cacheLocation": "10.186.170.131:7300", 
     "HotelList": { 
      "@activePropertyCount": "1157", 
      "@size": "1", 
      "HotelSummary": { 
       "@order": "0", 
       "hotelId": 403147, 
       "name": "Justabed - Hostel", 
       "address1": "38 avenue augustin dumont", 
       "city": "Malakoff", 
       "postalCode": 92240, 
       "countryCode": "FR", 
       "airportCode": " ", 
       "supplierType": "E", 
       "propertyCategory": 5, 
       "hotelRating": 0, 
       "confidenceRating": 52, 
       "amenityMask": 8, 
       "tripAdvisorRating": 1.5, 
       "locationDescription": "Near Paris Expo Porte de Versailles", 
       "shortDescription": "<p><b>Property Location</b> <br />With a stay at Justabed in Vanves, you'll be close to Stade de la Plaine and Eiffel Tower.<br/> This hostel is within close proximity of Georges Brassens Park and", 
       "highRate": 24.87, 
       "lowRate": 24.87, 
       "rateCurrencyCode": "EUR", 
       "latitude": 48.81804, 
       "longitude": 2.30196, 
       "proximityDistance": 2.5680416, 
       "proximityUnit": "MI", 
       "hotelInDestination": true, 
       "thumbNailUrl": "/hotels/5000000/4850000/4849100/4849100/4849100_7_t.jpg", 
       "deepLink": "http://travel.ian.com/index.jsp?pageName=hotAvail&cid=55505&hotelID=403147&mode=2&numberOfRooms=1&room-0-adult-total=1&room-0-child-total=0&arrivalMonth=8&arrivalDay=18&departureMonth=8&departureDay=21&showInfo=true&locale=en_US&currencyCode=EUR", 
       "RoomRateDetailsList": { 
        "RoomRateDetails": { 
         "roomTypeCode": 200166353, 
         "rateCode": 201887482, 
         "maxRoomOccupancy": 1, 
         "quotedRoomOccupancy": 1, 
         "minGuestAge": 3, 
         "roomDescription": "Single Beds in Mixed Dormitory Room - Non refundable", 
         "currentAllotment": 8, 
         "propertyAvailable": true, 
         "propertyRestricted": false, 
         "expediaPropertyId": 4849100, 
         "rateKey": "0ABAAA83-04C7-5B91-40A2-754D72994DA3", 
         "RateInfo": { 
          "@rateChange": "false", 
          "@promo": "false", 
          "@priceBreakdown": "true", 
          "ChargeableRateInfo": { 
           "@total": "79.83", 
           "@surchargeTotal": "5.22", 
           "@nightlyRateTotal": "74.61", 
           "@maxNightlyRate": "24.87", 
           "@currencyCode": "EUR", 
           "@commissionableUsdTotal": "99.65", 
           "@averageRate": "24.87", 
           "@averageBaseRate": "24.87", 
           "NightlyRatesPerRoom": { 
            "@size": "3", 
            "NightlyRate": [ 
             { 
              "@promo": "false", 
              "@rate": "24.87", 
              "@baseRate": "24.87" 
             }, 
             { 
              "@promo": "false", 
              "@rate": "24.87", 
              "@baseRate": "24.87" 
             }, 
             { 
              "@promo": "false", 
              "@rate": "24.87", 
              "@baseRate": "24.87" 
             } 
            ] 
           }, 
           "Surcharges": { 
            "@size": "1", 
            "Surcharge": { 
             "@amount": "5.22", 
             "@type": "TaxAndServiceFee" 
            } 
           } 
          } 
         }, 
         "ValueAdds": { 
          "@size": "1", 
          "ValueAdd": { 
           "@id": "2048", 
           "description": "Free Wireless Internet" 
          } 
         } 
        } 
       } 
      } 
     } 
    } 
} 
+1

비슷한 질문이 있습니다. http://stackoverflow.com/a/1710231/864571 – jaesanx

답변

0

이 여기 아마 다른 사람들을 위해 유용 할 것이다하는 대답

public void parseLink(String jsonObject) { 
     try { 
      ObjectMapper mapper = new ObjectMapper(); 
      JsonFactory factory = mapper.getJsonFactory(); // since 2.1 use mapper.getFactory() instead 
      JsonParser jp = factory.createJsonParser(jsonObject); 
      JsonNode input = mapper.readTree(jp); 

     // final JsonNode results = input.get("HotelListResponse").get("HotelList").get("HotelSummary"); 

      Iterator<Entry<String, JsonNode>> nodeIterator = input.get("HotelListResponse").getFields(); 

      while (nodeIterator.hasNext()) { 
       Map.Entry<String, JsonNode> entry = (Map.Entry<String, JsonNode>) nodeIterator.next(); 
       System.out.println("key --> " + entry.getKey() + " value-->" + entry.getValue()); 

      } 

      Iterator<Entry<String, JsonNode>> nodeIterator1 = input.get("HotelListResponse").get("HotelList").getFields(); 

      while (nodeIterator1.hasNext()) { 
       Map.Entry<String, JsonNode> entry = (Map.Entry<String, JsonNode>) nodeIterator1.next(); 
       System.out.println("key --> " + entry.getKey() + " value-->" + entry.getValue()); 

      } 

      Iterator<Entry<String, JsonNode>> nodeIterator2 = input.get("HotelListResponse").get("HotelList").get("HotelSummary").getFields(); 

      while (nodeIterator2.hasNext()) { 
       Map.Entry<String, JsonNode> entry = (Map.Entry<String, JsonNode>) nodeIterator2.next(); 
       System.out.println("key --> " + entry.getKey() + " value-->" + entry.getValue()); 

      } 




     } catch (IOException ex) { 
      Logger.getLogger(HotelBean.class.getName()).log(Level.SEVERE, null, ex); 
     } catch (Exception e) { 
      e.printStackTrace(); 
     } 

    } 
1

내 JSON의 예입니다 (다른 사람이 거기에 있습니다,. 그게 내가 웹 검색 발견 단지 첫번째 하나)를

물론 이것은 학교 프로젝트이거나 뭔가가 아니라면 자신 만의 파서를 작성해야합니다. 이 경우 좀 더 구체적인 질문을하고 모든 것을하는 법을 묻는 대신 질문해야합니다.

4

Java에서 JSON을 구문 분석하기 위해 알고있는 두 개의 라이브러리, GSON과 Jackson이 있습니다. 나는 잭슨에 대해 조금 알고는 3 가지 방식으로 작동합니다

  1. 당신이 그것을 탐색 할 수 있습니다, 그래서 당신은
  2. 당신은 당신의 JSON을 읽고 메모리에로드 할 수있는 객체로 JSON을 구문 분석 잭슨을 요청할 수 있습니다 . 이러한 방법에 대한 링크
  3. 당신은 스트림 여기

처럼 JSON을 읽을 수있다 : 나는 요약과 잭슨을 사용 http://wiki.fasterxml.com/JacksonInFiveMinutes