这是个完整的例子完整复制就能运行
gson解析需要一个架包,我上传好了,免积分下载地址
http://download.csdn.net/detail/zhaihaohao1/8247589
项目结构
java代码
MainActivity
package com.zhh.android;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.List;
import org.json.JSONArray;
import org.json.JSONObject;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import android.os.Bundle;
import android.app.Activity;
import android.util.Log;
import android.view.Menu;
public class MainActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
String str = getdata1();
parseJSONWithGSON1(str);
String str2 = getdata2();
parseJSONWithGSON2(str2);
}
/**
* 生成json
* {"id":"1","age":"10","name":"关羽"}
*
*/
public String getdata1() {
String jsonStr = null;
try {
JSONObject object = new JSONObject();
object.put("id", "1");
object.put("name", "关羽");
object.put("age", "10");
jsonStr = object.toString();
// 看到json格式的数据
Log.i("1", "json格式的数据" + jsonStr);
} catch (Exception e) {
e.printStackTrace();
}
return jsonStr;
}
/**
* 解析json数据
*/
private void parseJSONWithGSON1(String str) {
Gson gson =new Gson();
Person person=gson.fromJson(str, Person.class);
Log.i("1", person.getId());
Log.i("1", person.getName());
Log.i("1", person.getAge());
}
/**
* 生成json
* [{"id":"1","age":"10","name":"关羽"},{"id":"2","age":"20","name":"张飞"}]
*
*/
public String getdata2(){
String objectrootStr =null;
try {
JSONArray array = new JSONArray();
JSONObject object1 = new JSONObject();
object1.put("id", "1");
object1.put("name", "关羽");
object1.put("age", "10");
array.put(object1);
JSONObject object2 = new JSONObject();
object2.put("id", "2");
object2.put("name", "张飞");
object2.put("age", "20");
array.put(object2);
objectrootStr = array.toString();
// 看到json格式的数据
Log.i("1", "json格式的数据" + objectrootStr);
} catch (Exception e) {
e.printStackTrace();
}
return objectrootStr;
}
/**
* 解析json数据
*/
private void parseJSONWithGSON2(String str) {
Gson gson =new Gson();
List<Person>personlist=gson.fromJson(str, new TypeToken<List<Person>>(){}.getType());
for (Person person:personlist) {
Log.i("1", person.getId());
Log.i("1", person.getName());
Log.i("1", person.getAge());
}
javabean
package com.zhh.android;
public class Person {
public String id;
public String name;
public String age;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getAge() {
return age;
}
public void setAge(String age) {
this.age = age;
}
}
}
}// class