直接上代码
主程序代码:
package com.cc.mygson;
import java.net.Proxy.Type;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
public class MainActivity extends Activity{
String json = "{\"total\":100,\"rows\":[{\"key\":\"key1\",\"value\":\"value1\"},{\"key\":\"key2\",\"value\":\"value2\"}]}";
private Gson gson;
@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.layotu);
gson = new Gson();
findViewById(R.id.btn).setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
gsonMyJSONType();
}
});
}
/**
*基础JSON解析方法
*/
private void gsonJson() {
try {
JSONObject jsonObject = new JSONObject(json);
int total = jsonObject.getInt("total");
JSONArray array = jsonObject.getJSONArray("rows");
for(int i = 0 ;i<array.length();i++){
String key = array.getJSONObject(i).getString("key");
String value = array.getJSONObject(i).getString("value");
}
} catch (JSONException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
/**
*一般Gson解析方法
*/
private void gsonMyJSON(){
MyJson myJson = gson.fromJson(json, MyJson.class);
int total = myJson.getTotal();
}
/**
* 一般Type Gson解析方法
*/
private void gsonMyJSONType(){
java.lang.reflect.Type type = new TypeToken<MyJson>(){}.getType();
MyJson myJson = gson.fromJson(json, type);
int total = myJson.getTotal();
}
}
package com.cc.mygson;
import java.util.ArrayList;
public class MyJson {
private int total;
private ArrayList<Rows> rows = new ArrayList<Rows>();
public int getTotal() {
return total;
}
public void setTotal(int total) {
this.total = total;
}
public ArrayList<Rows> getRows() {
return rows;
}
public void setRows(ArrayList<Rows> rows) {
this.rows = rows;
}
}
Rows类内容为下:
package com.cc.mygson;
public class Rows {
private String key ;
private String value ;
public String getKey() {
return key;
}
public void setKey(String key) {
this.key = key;
}
public String getValue() {
return value;
}
public void setValue(String value) {
this.value = value;
}
}