使用JSON解析
问题描述:
{
"user": {
"name": ["bineesh", "Administrator", "binu", "binu", "bijith", "prem"]
},
"email": ["[email protected]", "[email protected]", "[email protected]", "[email protected]", "[email protected]", "[email protected]"],
"phone": ["7293553814", "12345", "0", "0", "0", "9046567239"]
}
我无法分析这种反应,我不能检索数据?使用JSON解析
答
示例代码:
public void parse(String s){
try {
JSONObject jsonObject = new JSONObject(s);
JSONObject namejObj = jsonObject.getJSONObject("user");
JSONArray nameArray = namejObj.getJSONArray("name");
for(int i =0;i<nameArray.length();i++){
Log.i("System out","name : "+nameArray.getString(i).toString());
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
答
您可以使用以下方法来解析JSON文件
JSONObject obj = new JSONObject(result);
JSONObject objUser = obj.getJSONObject("user");
JSONArray arrUser = objUser.getJSONArray("name");
for(int i=0;i<arrUser.length();i++)
{
String name = arrUser.getString(i);
}
JSONArray arrEmail = objUser.getJSONArray("email");
for(int i=0;i<arrEmail.length();i++)
{
String email = arrEmail.getString(i);
}
JSONArray arrPhone = objUser.getJSONArray("phone");
for(int i=0;i<arrPhone.length();i++)
{
String phone = arrPhone.getString(i);
}
答
示例代码:
public class HomeActivity extends ListActivity {
/** Called when the activity is first created. */
@SuppressWarnings({ "rawtypes", "unchecked" })
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setListAdapter(new ArrayAdapter(this, android.R.layout.simple_list_item_1, this.fetchTwitterPublicTimeline()));
}
public ArrayList<String> fetchTwitterPublicTimeline()
{
ArrayList<String> listItems = new ArrayList<String>();
try {
URL twitter = new URL(
"http://twitter.com/statuses/public_timeline.json");
URLConnection tc = twitter.openConnection();
BufferedReader in = new BufferedReader(new InputStreamReader(
tc.getInputStream()));
String line;
while ((line = in.readLine()) != null) {
JSONArray ja = new JSONArray(line);
for (int i = 0; i < ja.length(); i++) {
JSONObject jo = (JSONObject) ja.get(i);
listItems.add(jo.getString("text"));
}
}
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return listItems;
}
}
+0
雅我非常感谢你 – Bineesh 2011-12-30 12:43:04
你应该试着先了解JSON的基础知识,如何解析它。 – 2011-12-29 11:48:57
http://stackoverflow.com/questions/8667181/parse-multiple-objects-with-gson也可以使用Gson – 2011-12-29 11:58:38