215k views
3 votes
This is a coding project. Write an Android application that gGiven the JSON string below, write the snippet of code that parses for:

The value of "country"
The value of "temp" and then display on the screen
{
"sys":
{
"country":"GB",
"sunrise":1381107633,
"sunset":1381149604
},
"weather":[
{
"id":711,
"main":"Smoke",
"description":"smoke",
"icon":"50n"
}
],
"main":
{
"temp":304.15,
"pressure":1009,
}
}

1 Answer

6 votes

Final answer:

The code snippet involves parsing a JSON string using the org.json library in an Android application to extract the values of "country" and "temp" and then displaying them on the screen within a TextView.

Step-by-step explanation:

To parse the JSON string provided and display the values of "country" and "temp", you can use the following code snippet. First, you'd need to add the JSON parsing library dependency to your project, for example, Gson or org.json. Below, I'm showing how you could use org.json library for JSON parsing in an Android application:

try {
JSONObject jsonObject = new JSONObject(jsonString);
String country = jsonObject.getJSONObject("sys").getString("country");
double temp = jsonObject.getJSONObject("main").getDouble("temp");
// Use these variables to display on the screen
// For example, setting them on a TextView:
// textView.setText("Country: " + country + "\\Temperature: " + temp);
} catch (JSONException e) {
e.printStackTrace();
}

Please ensure to handle JSON parsing inside a try-catch block to catch JSONExceptions, and also make sure you have the appropriate permissions and view elements set up in your Android application to display text on the screen.

User Zakir Sheikh
by
7.8k points