14

我试图从 JSON 字符串中获取一个值,但我得到的是一个空值。

应用程序2.java:

package JsonExample1;

import org.codehaus.jackson.JsonNode;
import org.codehaus.jackson.map.ObjectMapper;

import java.io.IOException;
import java.io.StringReader;

public class App2 {

    private JsonNode rootNode;

    public void setup() throws IOException {
        String jsonString = "{\n" +
                "                \"HotelListResponse\" : {\n" +
                "                    \"customerSessionId\" : \"0ABAAA7A-90C9-7491-3FF2-7E2C37496CA2\",\n" +
                "                    \"numberOfRoomsRequested\" : 1,\n" +
                "                    \"moreResultsAvailable\" : true,\n" +
                "                    \"cacheKey\" : \"7790c974:13ff7e2c374:6ccd\",\n" +
                "                    \"cacheLocation\" : \"10.186.170.122:7300\",\n" +
                "                    \"HotelList\" : {\n" +
                "                        \"@activePropertyCount\" : \"223\",\n" +
                "                        \"@size\" : \"1\",\n" +
                "                        \"HotelSummary\" : {\n" +
                "                            \"@order\" : \"0\",\n" +
                "                            \"hotelId\" : 125727,\n" +
                "                            \"name\" : \"Red Lion Hotel on Fifth Avenue\",\n" +
                "                            \"address1\" : \"1415 5th Ave\",\n" +
                "                            \"city\" : \"Seattle\",\n" +
                "                            \"stateProvinceCode\" : \"WA\",\n" +
                "                            \"postalCode\" : 98101,\n" +
                "                            \"countryCode\" : \"US\",\n" +
                "                            \"airportCode\" : \"SEA\",\n" +
                "                            \"supplierType\" : \"E\",\n" +
                "                            \"hotelRating\" : 3.5,\n" +
                "                            \"propertyCategory\" : 1,\n" +
                "                            \"confidenceRating\" : 90,\n" +
                "                            \"amenityMask\" : 7847938,\n" +
                "                            \"tripAdvisorRating\" : 4,\n" +
                "                            \"locationDescription\" : \"Near Pike Place Market\",\n" +
                "                            \"shortDescription\" : \"<p><b>Location. </b> <br />Red Lion Hotel on Fifth Avenue is located close to 5th Avenue Theater, Pike Place Market, and Washington State Convention & Trade Center. Additional points of interest\",\n" +
                "                            \"highRate\" : 149,\n" +
                "                            \"lowRate\" : 126.65,\n" +
                "                            \"rateCurrencyCode\" : \"USD\",\n" +
                "                            \"latitude\" : 47.60985,\n" +
                "                            \"longitude\" : -122.33475,\n" +
                "                            \"proximityDistance\" : 11.168453,\n" +
                "                            \"proximityUnit\" : \"MI\",\n" +
                "                            \"hotelInDestination\" : true,\n" +
                "                            \"thumbNailUrl\" : \"/hotels/1000000/60000/51000/50947/50947_180_t.jpg\",\n" +
                "                            \"deepLink\" : \"http://travel.ian.com/index.jsp?pageName=hotAvail&cid=55505&hotelID=125727&mode=2&numberOfRooms=1&room-0-adult-total=2&room-0-child-total=0&arrivalMonth=8&arrivalDay=4&departureMonth=8&departureDay=5&showInfo=true&locale=en_US&currencyCode=USD\",\n" +
                "                            \"RoomRateDetailsList\" : {\n" +
                "                                \"RoomRateDetails\" : {\n" +
                "                                    \"roomTypeCode\" : 253461,\n" +
                "                                    \"rateCode\" : 201054304,\n" +
                "                                    \"maxRoomOccupancy\" : 2,\n" +
                "                                    \"quotedRoomOccupancy\" : 2,\n" +
                "                                    \"minGuestAge\" : 0,\n" +
                "                                    \"roomDescription\" : \"Classic Single Queen\",\n" +
                "                                    \"promoId\" : 202161947,\n" +
                "                                    \"promoDescription\" : \"Summer Sale! Save 15%\",\n" +
                "                                    \"currentAllotment\" : 0,\n" +
                "                                    \"propertyAvailable\" : true,\n" +
                "                                    \"propertyRestricted\" : false,\n" +
                "                                    \"expediaPropertyId\" : 50947,\n" +
                "                                    \"rateKey\" : \"0ABAAA7A-90C9-7491-3FF2-7E2C37496CCE\",\n" +
                "                                    \"RateInfo\" : {\n" +
                "                                        \"@rateChange\" : \"false\",\n" +
                "                                        \"@promo\" : \"true\",\n" +
                "                                        \"@priceBreakdown\" : \"true\",\n" +
                "                                        \"ChargeableRateInfo\" : {\n" +
                "                                            \"@total\" : \"151.23\",\n" +
                "                                            \"@surchargeTotal\" : \"24.58\",\n" +
                "                                            \"@nightlyRateTotal\" : \"126.65\",\n" +
                "                                            \"@maxNightlyRate\" : \"126.65\",\n" +
                "                                            \"@currencyCode\" : \"USD\",\n" +
                "                                            \"@commissionableUsdTotal\" : \"126.65\",\n" +
                "                                            \"@averageRate\" : \"126.65\",\n" +
                "                                            \"@averageBaseRate\" : \"149.0\",\n" +
                "                                            \"NightlyRatesPerRoom\" : {\n" +
                "                                                \"@size\" : \"1\",\n" +
                "                                                \"NightlyRate\" : {\n" +
                "                                                    \"@promo\" : \"true\",\n" +
                "                                                    \"@rate\" : \"126.65\",\n" +
                "                                                    \"@baseRate\" : \"149.0\"\n" +
                "                                                }\n" +
                "                                            },\n" +
                "                                            \"Surcharges\" : {\n" +
                "                                                \"@size\" : \"1\",\n" +
                "                                                \"Surcharge\" : {\n" +
                "                                                    \"@amount\" : \"24.58\",\n" +
                "                                                    \"@type\" : \"TaxAndServiceFee\"\n" +
                "                                                }\n" +
                "                                            }\n" +
                "                                        }\n" +
                "                                    },\n" +
                "                                    \"ValueAdds\" : {\n" +
                "                                        \"@size\" : \"1\",\n" +
                "                                        \"ValueAdd\" : {\n" +
                "                                            \"@id\" : \"2048\",\n" +
                "                                            \"description\" : \"Free Wireless Internet\"\n" +
                "                                        }\n" +
                "                                    }\n" +
                "                                }\n" +
                "                            }\n" +
                "                        }\n" +
                "                    }\n" +
                "                }\n" +
                "            }";

        rootNode = new ObjectMapper().readTree(new StringReader(jsonString));
    }

    //other methods
    public void basicTreeModelRead()
    {
        //Just like DOM, our data is in a hierarchy of node (in this case, it is JsonNode)
        JsonNode aField = rootNode.get("customerSessionId");

        //the customerSessionId has a String value
        String myString = aField.asText();

        System.out.println("customerSessionId is:" + myString);
    }
}

StartHere.java:

package JsonExample1;

import java.io.IOException;

public class StartHere {
    public static void main(String[] args) {

        App2 myApp = new App2();
        try {
            myApp.setup();
        } catch (IOException e) {
            e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
        }

        myApp.basicTreeModelRead();

    }
}

调试后我发现 aField 值仍然为空。有任何想法吗?

4

3 回答 3

28

您的根节点没有customerSessionId,它有HotelListResponse. 先得到那个。

//other methods
public void basicTreeModelRead()
{
    JsonNode innerNode = rootNode.get("HotelListResponse"); // Get the only element in the root node
    // get an element in that node
    JsonNode aField = innerNode.get("customerSessionId");

    //the customerSessionId has a String value
    String myString = aField.asText();

    System.out.println("customerSessionId is:" + myString);
}

这打印

customerSessionId is:0ABAAA7A-90C9-7491-3FF2-7E2C37496CA2
于 2013-07-25T15:37:10.810 回答
5

使用 .at() 方法获取内部元素的另一种方法:

rootNode.at("/HotelListResponse/customerSessionId")
于 2020-02-12T06:54:54.340 回答
0

转换为地图

Map map = objectMapper.readValue(jsonString, Map.class);

在地图中导航的方法

private static <T> T get(Map map, Class<T> clazz, String... path) {
    Map node = map;
    for (int i = 0; i < path.length - 1; i++) {
      node = (Map) node.get(path[i]);
    }
    return (T) node.get(path[path.length - 1]);
  }

用法:

String value = get(map, String.class, "path", "to", "the", "node")
于 2018-07-16T18:18:37.883 回答