android开发 - JSON解析

来源:互联网 发布:解说词配音软件 编辑:程序博客网 时间:2024/06/02 04:13


为了提高性能,最好用JSON格式


解析XML格式是需要时间的,








JAVA有专门解析JSON格式的类






import org.json.*;


 @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        
        
        
    String jsonString = "[" +
"{id:1,name:\"Victor\",age:20,city:\"北京\"}," +
"{id:2,name:\"Silver\",age:21,city:\"上海\"}," +
"{id:3,name:\"Jon\",age:22,city:\"武汉\"}]";

List<HashMap<String,Object>> list = new ArrayList<HashMap<String,Object>>(); 
try {
JSONArray jsonArray = new JSONArray(jsonString);
for(int i=0;i<jsonArray.length();i++){
JSONObject jsonObject = jsonArray.getJSONObject(i);
HashMap<String,Object> map = new HashMap<String, Object>();
map.put("id", jsonObject.getInt("id"));
map.put("name", jsonObject.getString("name"));
map.put("age", jsonObject.getInt("age"));
map.put("city", jsonObject.getString("city"));
list.add(map);

} catch (JSONException e) { 
e.printStackTrace();
}
for(HashMap<String,Object> hashMap : list){
System.out.println("id="+hashMap.get("id")+",name="+
hashMap.get("name")+",age="+
hashMap.get("age")+",city="+
hashMap.get("city"));
}
    }























































































0 0
原创粉丝点击