JSON01

package mars.json;



import android.R;
import android.support.v4.app.Fragment;
import android.app.Activity;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.Button;
import android.os.Build;

public class MainActivity extends Activity {

	private String jsonData = "[{\"name\":\"Micheal\"},{\"name\":\"Mike\":21}]";
	private Button button;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_list_item);
		button = (Button)findViewById(R.id.button1);
		button.setOnClickListener(new ButtonListener());
	}
	
	private class ButtonListener implements OnClickListener{

		@Override
		public void onClick(View v) {
			// TODO Auto-generated method stub
			JsonUtils jsonUtils = new JsonUtils();
			jsonUtils.parseJson(jsonData);
		}
		
	}
}

package mars.json;

import java.io.StringReader;

import android.util.JsonReader;

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.print("name--->" + reader.nextString());
					}
					else if(tagName.equals("age")){
						System.out.println("age--->" + reader.nextInt());
					}
				}
				reader.endObject();
			}
			reader.endArray();
		}catch(Exception e){
			e.printStackTrace();
		}
	}
}

你可能感兴趣的:(json)