这应该非常简单,而且我已经接近搞清楚,但我开始放松自己的理智。 只是尝试从api中提取数据
如何从对象(另一个对象内)中提取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<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");
}
}
答案 0 :(得分:1)
您可以尝试使用gson库来解析响应。在build.gradle中添加以下内容
compile group: 'com.google.code.gson', name: 'gson', version: '2.3.1'
创建bean以匹配您的响应。使用字段来匹配json响应中返回的内容。以下示例。
public class ResultsResponse {
private List<MyList> list;
}
public class MyList {
private String main;
}
如果您希望MyList
可以有另一个列表。最后试试
GsonBuilder gsonBuilder = new GsonBuilder();
ResultsResponse response = gsonBuilder.create().fromJson(jsonString, ResultsResponse.class)
response
对象应填充您的列表。