日期:2014-05-16  浏览次数:20442 次

Android学习笔记_Json数据的解析
JSON数据的解析
例子:

public class ParseJsonActivity extends Activity{
     private String jsonData="[{\"name\":\"michael\",\"age\":20},{\"name\":\"mike\",\"age\":22}]";
     private Button button;
     public void onCreate(Bundle saveInstanceState){
        super.onCreate(saveInstanceState);
        setContentView(R.layout.main);
        button=(Button)findViewById();
        button.setOnClickListener(new ButtonListener());
     }
     private class ButtonListener implements OnClickListener{
         public void onClick(View v){
             JsonUtils jsonUtils=new JsonUtils();
             jsonUtils.parseJson(jsonData);
         }
     }
}


public class JsonUtils{
    public void parseJson(String jsonData){
        try{
            JsonReader reader = new JsonReader(new StringReader(jsonData));
            reader.beginArray();
            while(reader.hasNext()){
                 reader.beginObject();
                 while(reader.hasNext()){
                     String tagName=reader.nextName();
                     if(tagName.equals("name")){
                           System.out.println("name--->"+reader.nextString());
                     }else if(tagName.equals("age")){
                           System.out.println("age--->"+reader.nextInt());
                     }
                 }
                 reader.endObject();
            }
            reader.endObject();
        }catch(Exception e){
           e.printStackTrace();
        }
    }
}