首先是从服务器获取Json数据
public void GetJsonData(final Map<String, String> params) throws Exception {
String result = null;
new Thread(new Runnable() {
@Override
public void run() {
if (params != null) {
// 设置请求数据时需要的传参
_url = _url + "?" + "uid=" + params.get("uid") + "&puid="
+ params.get("puid");
}
HttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(_url);
try {
// 获取HTTPResponse实例
HttpResponse hResponse = httpClient.execute(httpPost);
if (hResponse.getStatusLine().getStatusCode() == 200) {
String result = EntityUtils.toString(
hResponse.getEntity(), "UTF_8");
Log.i("json数据", result);
} else {
Log.i("HttpPost", "HttpPost 方式请求失败");
}
} catch (Exception e) {
e.printStackTrace();
}
}
}).start();
}
获取数据后,就可以对Json数据进行反序列化,一般Json数据有两种格式:
一种是[ {"id":1,"name":"小猪" ,"age”:22} , {"id":2,"name":"小猫","age”:23} , .......]这样的数据组;
另一种是{"id":1,"name":"小猪" ,"age”:22}这样的由key、value组成的数据。
两种数据都可以由一对象类解析,只是解析类型不一样,这里我用User对象类来解析,所以要创建一User类对象:
private int uid;
private String uName;
private int sex;
private int age;
private String zhiwei;
public int getUid() {
return uid;
}
public void setUid(int uid) {
this.uid = uid;
}
public String getuName() {
return uName;
}
public void setuName(String uName) {
this.uName = uName;
}
public int getSex() {
return sex;
}
public void setSex(int sex) {
this.sex = sex;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getZhiwei() {
return zhiwei;
}
public void setZhiwei(String zhiwei) {
this.zhiwei = zhiwei;
}
Gson是Google 提供的用来在 Java 对象和 JSON 数据之间进行映射的 Java 类库。可以将一个 JSON 字符串转成一个 Java 对象,或者反过来。所以Json数据我使用Gson库连解析,解析之前首先要把jar包考到项目中。
Gson网址http://code.google.com/p/google-gson/
之后就可以利用Gson 对Json数据进行解析
/**
* Json 数据反序列化
*
*/
public static Object toObject(String jsonString, Object type) {
Gson gson = new Gson();// 创建Gson对象
if (type instanceof Class<?>) {
try {
return gson.fromJson(jsonString, (Class<?>) type);
} catch (JsonSyntaxException e) {
e.printStackTrace();
return null;
}
} else if (type instanceof Type) {
try {
return gson.fromJson(jsonString, (Type) type);
} catch (JsonSyntaxException e) {
e.printStackTrace();
return null;
}
} else {
throw new RuntimeException("只能是Class<?>或者通过TypeToken获取的Type类型");
}
}