这应该是非常简单的,我已经越来越接近找出它,但我开始放松我的理智。 只是试图从api中提取数据JSON解析在android中:打开对象内的对象
如何从一个对象(在另一个对象内)拉出JSON数据?
这是我听说过JSON的第一天,所以生病时第一个承认我对此知之甚少。谢谢你的时间!
这篇文章:JSON parsing in android: No value for x error是超级有用的,让我到现在我正在试图打开“列表”,然后进入“0”,所以我可以收集天气数据。
使用jsonviewer.stack一直试图了解这个东西
我的代码:
公共类MainActivity扩展AppCompatActivity {
TextView citySpot;
TextView cityTemp;
public class DownloadTask extends AsyncTask {
@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");
}
}
+0
[如何在Android中解析JSON]可能的重复(http://stackoverflow.com/questions/9605913/how-to-parse-json-in-android) –
+1
'['启动一个数组。 '{'启动一个对象。没有对象的键是“0”,列表映射到数组。 –
+1
“container”和“listTest”是相等的,所以你只需要前者 –