本文来自http://tonysun3544.iteye.com/category/188238
package com.tony.json;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
public class JsonActivity extends Activity {
/* Called when the activity is first created. /
private String jsonData = "[{"name":"zhangsan","age":22},{"name":"lisi","age":23}]";
private Button jsonButton;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
jsonButton = (Button) findViewById(R.id.json_button);
jsonButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
JsonUtils jsonUtils = new JsonUtils();
jsonUtils.parseJson(jsonData);
}
});
}
}
这个类中主要是解析json数组:
Java代码 收藏代码
package com.tony.json;
import java.io.IOException;
import java.io.StringReader;
import android.util.Log;
import com.google.gson.stream.JsonReader;
public class JsonUtils {
private static final String TAG = “JsonUtils”;
public void parseJson(String jsonData){
JsonReader reader = new JsonReader(new StringReader(jsonData));
try {
reader.beginArray(); // 開始解析数组
while (reader.hasNext()) {
reader.beginObject(); // 開始解析对象
while (reader.hasNext()) {
String tagName = reader.nextName(); // 得到键值对中的key
if (tagName.equals("name")) { // key为name时
Log.i(TAG, "name--------->" + reader.nextString()); // 得到key中的内容
}else if (tagName.equals("age")) { // key为age时
Log.i(TAG, "age--------->" + reader.nextInt()); // 得到key中的内容
}
}
reader.endObject();
}
reader.endArray();
} catch (IOException e) {
e.printStackTrace();
}
}
}