本例用JsonReader类来解析json数据。用Gson解析json数据参见json数据解析二一文。
当然是用google的api我们要引入google-gson jar包。
在res/layout/main.xml中添加一个Button按钮:
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width="fill_parent" android:layout_height="fill_parent" > <Button android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="开始Json解析" android:id="@+id/button" /> </LinearLayout>
由于比较简单,直接上代码,代码如下:
import java.io.StringReader;
import com.google.gson.stream.JsonReader;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
public class JsonTestMy extends Activity {
private Button button = null;
private String JsonData = "[{\"name\":\"huangwei\",\"age\":24,\"name\":\"lisi\",\"age\":36}]";
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
button = (Button) findViewById(R.id.button);
//设置button监听器
button.setOnClickListener(new OnClickListener() {//
@Override
public void onClick(View v) {
try {
JsonUtils.parseJsonData(JsonData);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
}
class JsonUtils {
public static void parseJsonData(String str) throws Exception {
//获取JsonReader对象
JsonReader jsonReader = new JsonReader(new StringReader(str));
//开始读取数组
jsonReader.beginArray();
//判断数组内是否有下一个object
while (jsonReader.hasNext()) {
//开始读objcet
jsonReader.beginObject();
//判断Object是否有下一个元素
while (jsonReader.hasNext()) {
String tag = jsonReader.nextName();
if (tag.equals("name")) {
System.out.println("name--------->" + jsonReader.nextString());
}
if (tag.equals("age")) {
System.out.println("age--------->" + jsonReader.nextInt());
}
}
jsonReader.endObject();
}
jsonReader.endArray();
}
}
以上就是使用JsonReader对象读取json数据。