【发布时间】:2016-03-04 09:05:53
【问题描述】:
我是 json 新手。我的问题很简单。我的 json 文件中有一些数组,还有一个字符串类型的数据。
现在我想从 json 文件中获取我的 java 类中的单个文本名称:anounce。 我怎样才能从 json 得到这个字符串? 或任何其他方式来获得这个?
Json 文件
[{
"title": "KalerKantha | OfftechIT",
"image": "",
"link": "http://www.kalerkantho.com/"
}, {
"title": "Prothom Alo | OfftechIT",
"image": "",
"link": "http://www.prothom-alo.com/"
},
...
{
"anounce": "I need this this text"
}
]
Java 代码
JsonArrayRequest movieReq = new JsonArrayRequest(url, new Response.Listener<JSONArray>() {
@Override
public void onResponse(JSONArray response) {
Log.d(TAG, response.toString());
hidePDialog();
// Parsing json
for (int i = 0; i < response.length(); i++) {
try {
JSONObject obj = response.getJSONObject(i);
Movie movie = new Movie();
movie.setTitle(obj.getString("title"));
movie.setThumbnailUrl(obj.getString("image"));
movie.setLink(obj.getString("link").toString());
// adding movie to movies array
movieList.add(movie);
} catch (JSONException e) {
e.printStackTrace();
}
}
// notifying list adapter about data changes
// so that it renders the Grid view with updated data
adapter.notifyDataSetChanged();
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
if (error instanceof NoConnectionError){
hidePDialog();
Toast.makeText(getActivity(), " No Internet connection! \n Please check you connection", Toast.LENGTH_LONG).show();
}};
});
【问题讨论】:
-
它是否总是在数组的最后一个对象中?
-
不,这是一个单一的对象。
-
检查 obj.has("anounce") 然后添加其他明智的忽略您可以对所有对象执行此操作
-
然后发布完整的 json。从您的 json 来看,它看起来像是数组的最后一个元素。
-
你可能对Gson感兴趣,太棒了。