// 先导入gson的jar包
// gson的一般使用方法
// class的属性名必须与json字符串中的key大小写完全一致
//解析JSONArray
private void parseJSONArray()
{
String jsonArr = "[{'key1':'value1', 'key2':'value2'}, {'key1':'value1', 'key2':'value2'}]";
Gson gson = new Gson();
java.lang.reflect.Type type = new com.google.gson.reflect.TypeToken<List<JsonData>>()
{
}.getType();
List<JsonData> fromJson = gson.fromJson(jsonArr, type);
mTextView.setText(fromJson.toString());
}
//解析JSONObject
private void parseJSONObject()
{
String jsonObj = "{'key1':'value1', 'key2':'value2'}";
Gson gson = new Gson();
JsonData jsonData = gson.fromJson(jsonObj, JsonData.class);
mTextView.setText(jsonData.toString());
}
class JsonData//属性必须与json里面的key一致
{
String key1;
String key2;
@Override
public String toString()
{
return "JSON1 [key1=" + key1 + ", key2=" + key2 + "]";
}
}
注:
1.参数类型不能是ArrayList,而是List
public class TestJson
{
public int Id;
public String Name;
public ParamJson EstateParam;
public List<String> Banners;//此处参数类型不能是ArrayList,而是List
}
public class ParamJson
{
public int Id;
public String Name;
public List<String> ListData;
}
解析只要一句代码即可:
TestJson mJson = ((TestJson) new Gson().fromJson(str, TestJson.class));