简体   繁体   中英

JSON parsing in android: opening objects inside objects

This should be really simple and i've been getting close to figuring it out but am starting to loose my sanity. Simply trying to pull data from an api

How do i pull JSON data from an object (inside another object)?

This is the first day i've ever heard of JSON so ill be the first to admit i have very little knowledge about this. Thanks for your time!

This post: JSON parsing in android: No value for x error was super helpful and got me to where i am now which is trying to open "list" then get into "0" so i can gather weather data.

Been using jsonviewer.stack to try to understand this stuff

Api url: http://api.openweathermap.org/data/2.5/forecast/city?id=4161254&APPID=e661f5bfc93d47b8ed2689f89678a2c9

My code:

public class MainActivity extends AppCompatActivity {

TextView citySpot;
TextView cityTemp;

public class DownloadTask extends AsyncTask<String, Void, String> {

    @Override
    protected String doInBackground(String... urls) {

        String result = "";
        URL url;
        HttpURLConnection urlConnection = null;

        try {

            url = new URL(urls[0]);

            urlConnection = (HttpURLConnection) url.openConnection();

            InputStream in = urlConnection.getInputStream();

            InputStreamReader reader = new InputStreamReader(in);

            int data = reader.read();

            while (data != -1) {

                char current = (char) data;

                result += current;

                data = reader.read();

            }
            return result;

        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;

    }

    @Override
    protected void onPostExecute(String result) {
        super.onPostExecute(result);

        try {

            // this works flawlessly and gathers the city name
            JSONObject container = new JSONObject(result);

            JSONObject cityTest = container.getJSONObject("city");

            citySpot.setText(cityTest.getString("name"));

            // this is my failed attempt to get inside of the "list" folder

            JSONObject listList = new JSONObject(result);

            JSONObject listTest = listList.getJSONObject("list");

            JSONObject listTestOne = listTest.getJSONObject("0");

            JSONObject listTestTwo = listTestOne.getJSONObject("main");

            cityTemp.setText(listTestTwo.getString("temp"));
        }
        catch (JSONException e) {
            e.printStackTrace();
        }
    }
}
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);


    citySpot = (TextView) findViewById(R.id.cityName);
    cityTemp = (TextView) findViewById(R.id.textView3);

    DownloadTask task = new DownloadTask();

        task.execute("http://api.openweathermap.org/data/2.5/forecast/city?id=4161254&APPID=e661f5bfc93d47b8ed2689f89678a2c9");


}

}

You could try use gson library to parse the response. Add below in build.gradle

compile group: 'com.google.code.gson', name: 'gson', version: '2.3.1'

Create beans to match your response. Use fields to match what comes back in the json response. Sample below.

public class ResultsResponse {
    private List<MyList> list;
}
public class MyList {
    private String main;
}

If you want MyList can have another list. Finally try

GsonBuilder gsonBuilder =  new GsonBuilder();
ResultsResponse response = gsonBuilder.create().fromJson(jsonString, ResultsResponse.class)

response object should have your list populated.

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