简体   繁体   中英

JsonObject JsonArray parsing issue

I'm new to JSON, but have had success pulling data from a couple other JSON request. This one is giving me trouble. Any help or pointers would be appreciated.

This is the JSON request: http://api.wunderground.com/api/95e20de6002dc6f0/currenthurricane/view.json

That above pulls down the data I am wanting.

Below is my code that I am having trouble with:

public static ArrayList<CycloneData> extractFeatureFromJson(String cycloneJSON) {

    // Create an empty ArrayList to start adding Cyclones to
    ArrayList<CycloneData> cyclones = new ArrayList<>();

    // try to parse the cycloneJSON response string. If there's a problem with the way the JSON
    // is formatted, a JSONException exception object will be thrown.
    // Catch the exception, and print the error message to the logs.

    try {

        JSONObject rootJsonObject = new JSONObject(cycloneJSON);

        // Create JSONArray associated with the key called "currenthurricane", which represents
        // a list of cyclones from JSON response.
        JSONArray currentHurricaneArray = rootJsonObject.getJSONArray("currenthurricane");

        //Loop through each section in the currentHurricaneArray array & create an
        //{@link CycloneData} object for each one
        for (int i = 0; i < currentHurricaneArray.length(); i++) {
            //Get cyclone JSONObject at position i in the array
            JSONObject cycloneProperties = currentHurricaneArray.getJSONObject(i);
            //Extract “stormName_Nice” for Cyclone's name
            String name = cycloneProperties.optString("stormName_Nice");
            // Extract the value for the key called "url"
            String url = cycloneProperties.optString("url");
            int category = cycloneProperties.optInt("SaffirSimpsonCategory");
            CycloneData cyclone = new CycloneData(category, name, url);
            //Add new cyclone to list
            cyclones.add(cyclone);
        }

    } catch (JSONException e) {
        // If an error is thrown when executing any of the above statements in the "try" block,
        // catch the exception here, so the app doesn't crash. Print a log message
        // with the message from the exception.
        Log.e("Utils", "Problem parsing the cyclone JSON results", e);
    }

    // Return the list of cyclones
    return cyclones;
}

Using the debugger in Android Studio, I can see that currentHurricaneArray in: JSONArray currentHurricaneArray = rootJsonObject.getJSONArray("currenthurricane");

is getting the expected JSON array data.

When the for loop starts the JSONObject: JSONObject cycloneProperties = currentHurricaneArray.getJSONObject(i);

has the correct array info I'm looking for as well.

However, after that when it starts extracting Strings. String name = cycloneProperties.optString("stormName_Nice");

It returns nothing.

Debug shows: name = ""

I am able to get the info I want if I use a JSON Query tool, but I cannot figure out how to get it working in my code.

I'm certain my String extraction is wrong, I just cannot figure out how to make it right. Or maybe I'm wrong all they way up.

*************Good code Below*******************

Ok Gaëtan Maisse got me going. Below is what I did to get it working.

for (int i = 0; i < currentHurricaneArray.length(); i++) {
            //Get cyclone JSONObject at position i in the array
            JSONObject cycloneProperties = currentHurricaneArray.getJSONObject(i);

            // Extract "stormInfo" object
            JSONObject stormInfo = cycloneProperties.optJSONObject("stormInfo");
            //Extract “stormName_Nice” & "requesturl" for Cyclone's name and url
            String name = stormInfo.optString("stormName_Nice");
            String url = stormInfo.optString("requesturl");

            // Extract "Current" object
            JSONObject Current = cycloneProperties.optJSONObject("Current");
            // Extract "SaffirSimpsonCategory" key
            int category = Current.optInt("SaffirSimpsonCategory");

            CycloneData cyclone = new CycloneData(category, name, url);
            //Add new cyclone to list
            cyclones.add(cyclone);
        }

optString(String name, String fallback), Returns the value mapped by name if it exists, coercing it if necessary, or fallback if no such mapping exists. print fallback to test.if fallback is triggered then there is no key.This suggest either your json structure is malformed or your logic of parsing is unfit for the defined structure you are using.

You are missing JSON key stormInfo in your parsing process for stormName_Nice :

{
    "response": {
        "version": "0.1",
        "termsofService": "http://www.wunderground.com/weather/api/d/terms.html",
        "features": {
            "currenthurricane": 1
        }
    },
    "currenthurricane": [{
        "stormInfo": {
            "stormName": "Daniel",
            "stormName_Nice": "Hurricane Daniel",
            "stormNumber": "ep201204"
        },
        ...,
        "SaffirSimpsonCategory": 1,
        "url":"URL",
        ... 
    }]
}

It should better works with this:

JSONObject rootJsonObject = new JSONObject(cycloneJSON);

// Create JSONArray associated with the key called "currenthurricane", which represents
// a list of cyclones from JSON response.
JSONArray currentHurricaneArray = rootJsonObject.getJSONArray("currenthurricane");

//Loop through each section in the currentHurricaneArray array & create an
//{@link CycloneData} object for each one
for (int i = 0; i < currentHurricaneArray.length(); i++) {
    //Get cyclone JSONObject at position i in the array
    JSONObject cycloneProperties = currentHurricaneArray.getJSONObject(i);

    // Extract "stormInfo" object
    JSONObject stormInfo = cycloneProperties.getJSONObject("stormInfo");
    //Extract “stormName_Nice” for Cyclone's name
    String name = stormInfo.optString("stormName_Nice");

    // Extract other values from cycloneProperties
    String url = cycloneProperties.optString("url");
    int category = cycloneProperties.optInt("SaffirSimpsonCategory");
    CycloneData cyclone = new CycloneData(category, name, url);
    //Add new cyclone to list
    cyclones.add(cyclone);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM