Android中发起网络访问的方式,以及Json、Gson的网络解析

什么是JSON ?
JSON是一种轻量级的数据交换格式,采用完全独立于语言的文本格式,易于人阅读和编写,
同时也易于机器解析和生成(数据量相对较少,网络传输速度相对较快)。
JSON语法:
JSON语法有JSONObject与JSONArray之分
JSONArray(用于描述JSON数组):
--【JSONArray用于以JSON的格式描述数组数据】
--【JSONArray也有下标与长度的用法】
--【JSONArray中根据元素不同的类型有不同的格式:
属性值类型为字符串时,需要使用双引号;
属性值类型为数字、boolean、数组等类型时,不需要任何符号】
JSONObject(用于描述JSON对象):
--【JSONObject中所含有的属性使用key:value的方式存储】
--【JSONObject的属性之间使用“,”分割】
--【JSONObject中属性名必须使用双引号】
--【JSONObject中的属性值根据不同类型有不同的格式:
属性值类型为字符串时,需要使用双引号;
属性值类型为数字、boolean、数组等类型时,不需要任何符号】
JSON的语法事例:
{"programmers":[
{"firstName":"Brett","lastName":"McLaughlin","email":"aaaa"},
{"firstName":"Jason","lastName":"Hunter","email":"bbbb"},
{"firstName":"Elliotte","lastName":"Harold","email":"cccc"}
],
"authors":[
{"firstName":"Lsaac","lastName":"Asimov","genre":"sciencefiction"},
{"firstName":"Tad","lastName":"Williams","genre":"fantasy"},
{"firstName":"Frank","lastName":"Peretti","genre":"christianfiction"}
]
}

使用HC(HttpClient)/UC(HttpURLConnection)进行网络访问的基本步骤:


0. 申请权限 INTERNET访问权限


1. 任何网络访问的相关代码,必须在工作线程中执行!


2. 创建HC/UC对象


3. 声明发起网络访问的方式(GET/POST)


4. 进行网络连接


5. 获得服务器响应的结果


6. 解析结果,提取需要的内容


7. 解析结果要提交到UI线程进行呈现


利用HttpClient的POST方式发起带参数的请求
利用POST方式发起请求,参数要放到请求实体中,并且在请求头中添加对实体中参数的说明

JSON字符串的解析


1)可以使用String,就按照一个普普通通符串来进行数据的提取


2)JSONLib(apache)


   JSONLib中两个常用类:


   JSONObject,用来描述对象


   JSONArray,用了描述数组


   解析实例:


   {"result":"ok", 


     "data": [ 


         {"id":1, 


          "name":"zhangsan", 


          "salary":12345.0, 


          "age":12, 


          "gender":"m"},


         {"id":2, 


          "name":"zhangsan", 


          "salary":12345.0, 


          "age":12, 


          "gender":"m"}


         ] 
    }
   1)根据JSON字符串创建JSONObject对象


 JSONObject obj = new JSONObject(json字符串)


  2)根据需要提取的数据类型,调用obj对象的getXXX方法


  3)利用取出的各种数据,构建成一个Java实体类对象


   Emp emp = new Emp();


   emp.setAge(obj.getInt());


   emp.setName(obj.getString());

Android中JSON解析:
android sdk中为我们提供了org.json,可以用来解析json,
在android3.0又为在android.util包JsonReader和JsonWriter来进行json的解析和生成。
Json解析使用的一般步骤:
1.写一个实体类封装相关属性信息,并写相关属性的set、get方法
2.写一个JsonUtil类,Json字符串为发起网络访问后返回的字符串
package com.example.ems.util;

import java.util.ArrayList;
import java.util.List;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import com.example.ems.bean.Emp;

public class JsonUtil {
public static List<Emp> getAllEmps(String result){
try {
//根据JSON字符串创建JSONObject对象
JSONObject obj = new JSONObject(result);
//取出"data"键对应的值
JSONArray arr = obj.getJSONArray("data");
List<Emp> emps = new ArrayList<Emp>();
for(int i=0;i<arr.length();i++){
JSONObject jsonobj = arr.getJSONObject(i);
Emp emp = new Emp();
emp.setAge(jsonobj.getInt("age"));
emp.setGender(jsonobj.getString("gender"));
emp.setName(jsonobj.getString("name"));
emp.setSalary(jsonobj.getDouble("salary"));
emps.add(emp);
}
return emps;
} catch (JSONException e) {
e.printStackTrace();
throw new RuntimeException("JSON字符串解析出现异常");
}

}
}
3.写一个HttpUtil类,发起网络访问(两种网络访问方式),通过监听器回调结果
以员工登录系统为例:
package com.example.ems.util;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

import org.apache.http.Header;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.json.JSONArray;
import org.json.JSONObject;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.os.Handler;
import android.os.Looper;
import android.util.Log;

import com.example.ems.bean.Emp;
import com.example.ems.bean.User;
import com.example.ems.bean.ValueObject;
import com.example.ems.listener.OnAddEmpFinishListener;
import com.example.ems.listener.OnLoadEmpsFinishListener;
import com.example.ems.listener.OnLoginFinishListener;
import com.example.ems.listener.OnRefreshVertifyCodeListener;
import com.example.ems.listener.OnRegistFinishListener;

public class EmsUtil {


public static void registUser(Context context, final User user,
final OnRegistFinishListener listener) {
new AsyncTask<Void, Void, String>() {


@Override
protected String doInBackground(Void... params) {

try {
HttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost("http://172.60.50.82:8080/ems/regist.do");
//添加一个请求头,对请求实体中的参数做一个说明
post.setHeader("Content-Type", "application/x-www-form-urlencoded");
//在post中添加请求参数
//请求参数会添加在请求实体中
List<NameValuePair> parameters = new ArrayList<NameValuePair>();
parameters.add(new BasicNameValuePair("loginname", user.getName()));
parameters.add(new BasicNameValuePair("password", user.getPassword()));
parameters.add(new BasicNameValuePair("realname", user.getRealname()));
parameters.add(new BasicNameValuePair("email", user.getEmail()));
HttpEntity entity = new UrlEncodedFormEntity(parameters);
post.setEntity(entity);

HttpResponse resp = client.execute(post);
HttpEntity respEntity = resp.getEntity();
// InputStream is = respEntity.getContent();
//
// BufferedReader br = new BufferedReader(new InputStreamReader(is));
//
// String line = br.readLine();
//
// br.close();


String line = EntityUtils.toString(respEntity);

return line;

} catch (Exception e) {
e.printStackTrace();
}


return null;
}

protected void onPostExecute(String result) {
listener.onRegistFinish(result);
};

}.execute();


}

public static void registUser2(Context context,final User user, final OnRegistFinishListener listener){
//HttpURLConnection进行注册
new Thread(){
public void run() {
try {
URL url = new URL("http://172.60.50.82:8080/ems/regist.do");
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("POST");
connection.setDoInput(true);//接收服务器响应的内容
connection.setDoOutput(true);//要向服务器提交内容
//在请求头中,为请求实体中的内容做说明
connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
connection.connect();
//客户端向服务器提交参数
OutputStream out = connection.getOutputStream();
PrintWriter pw = new PrintWriter(out, true);
//String params = "loginname="+user.getName()+"&password="+user.getPassword()+"&realname="+user.getRealname()+"&email="+user.getEmail();
String params = getParams(user);
pw.print(params);
pw.close();
//客户端获取服务器的响应内容
InputStream in = connection.getInputStream();
BufferedReader br = new BufferedReader(new InputStreamReader(in));
final String result = br.readLine();
br.close();
//在主线程执行
new Handler(Looper.getMainLooper()).post(new Runnable() {

@Override
public void run() {
listener.onRegistFinish(result);
}
});

} catch (Exception e) {
e.printStackTrace();
}
};
}.start();


}

protected static String getParams(User user) {
Map<String,String> map = new HashMap<String, String>();
map.put("loginname", user.getName());
map.put("password", user.getPassword());
map.put("realname", user.getRealname());
map.put("email", user.getEmail());

StringBuilder sb = new StringBuilder();

for(Entry<String, String> entry:map.entrySet()){
sb.append(entry.getKey()).
append("=").
append(entry.getValue()).
append("&");
}

return sb.substring(0, sb.length()-1);
}

public static void getVertify(final OnRefreshVertifyCodeListener listener) {
new AsyncTask<Void, Void, ValueObject>(){

@Override
protected ValueObject doInBackground(Void... params) {
try {
HttpClient client = new DefaultHttpClient();
HttpGet get = new HttpGet("http://172.60.50.82:8080/ems/getCode.do");
HttpResponse resp = client.execute(get);
Header header = resp.getFirstHeader("Set-Cookie");
String value = header.getValue().split(";")[0];
HttpEntity entity = resp.getEntity();
InputStream is = entity.getContent();
Bitmap bitmap = BitmapFactory.decodeStream(is);
is.close();

ValueObject vo = new ValueObject();
vo.setBitmap(bitmap);
vo.setSessionid(value);

return vo;
} catch (Exception e) {
e.printStackTrace();
}

return null;
}
protected void onPostExecute(ValueObject result) {
listener.onRefreshFinished(result.getBitmap(),result.getSessionid());
};

}.execute();

}

public static void getVertify2(final OnRefreshVertifyCodeListener listener){
new Thread(){
public void run() {
try {
URL url = new URL("http://172.60.50.82:8080/ems/getCode.do");
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("GET");
connection.setDoInput(true);
connection.connect();

final String value = connection.getHeaderField("Set-Cookie").split(";")[0];
InputStream is = connection.getInputStream();
final Bitmap bitmap = BitmapFactory.decodeStream(is);
is.close();
new Handler(Looper.getMainLooper()).post(new Runnable() {

@Override
public void run() {
listener.onRefreshFinished(bitmap,value);
}
});
} catch (Exception e) {
e.printStackTrace();
}
};
}.start();
}

public static void login(final String loginname, final String password, final String code,final String sid,
final OnLoginFinishListener listener) {
new AsyncTask<Void, Void, String>(){

@Override
protected String doInBackground(Void... params) {
try {
HttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost("http://172.60.50.82:8080/ems/login.do");
post.setHeader("Content-Type","application/x-www-form-urlencoded");
post.setHeader("Cookie",sid);
List<NameValuePair> parameters = new ArrayList<NameValuePair>();
parameters.add(new BasicNameValuePair("loginname", loginname));
parameters.add(new BasicNameValuePair("password", password));
parameters.add(new BasicNameValuePair("code", code));
HttpEntity entity = new UrlEncodedFormEntity(parameters);
post.setEntity(entity);
HttpResponse resp = client.execute(post);
String result = EntityUtils.toString(resp.getEntity());
return result;

} catch (Exception e) {
e.printStackTrace();
}
return null;
}
protected void onPostExecute(String result) {
listener.onLoginFinish(result);
};
}.execute();
}
public static void login2(final String loginname, final String password, final String code,final String sid,
final OnLoginFinishListener listener) {
new Thread(){
public void run() {
try {
URL url = new URL("http://172.60.50.82:8080/ems/login.do");
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("POST");
connection.setDoInput(true);
connection.setDoOutput(true);
connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
connection.setRequestProperty("Cookie", sid);
connection.connect();
OutputStream out = connection.getOutputStream();
PrintWriter pw = new PrintWriter(out,true);
pw.write(getParams(loginname,password,code));
pw.close();
InputStream in = connection.getInputStream();
BufferedReader br = new BufferedReader(new InputStreamReader(in));
final String result = br.readLine();
br.close();
new Handler(Looper.getMainLooper()).post(new Runnable() {

@Override
public void run() {
listener.onLoginFinish(result);

}
});

} catch (Exception e) {
e.printStackTrace();
}
};
}.start();
}

protected static String getParams(String loginname, String password,
String code) {
Map<String , String> map = new HashMap<String, String>();
map.put("loginname", loginname);
map.put("password", password);
map.put("code", code);
StringBuilder sb = new StringBuilder();
for(Entry<String, String> entry:map.entrySet()){
sb.append(entry.getKey()).append("=").append(entry.getValue()).append("&");
}
return sb.substring(0,sb.length()-1);
}

public static void addEmp(final Emp emp, final OnAddEmpFinishListener listener) {
new AsyncTask<Void, Void, String>(){

@Override
protected String doInBackground(Void... params) {
try {
HttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost("http://172.60.50.82:8080/ems/addEmp");
post.setHeader("Content-Type","application/x-www-form-urlencoded");
List<NameValuePair> parameters = new ArrayList<NameValuePair>();
parameters.add(new BasicNameValuePair("name", emp.getName()));
parameters.add(new BasicNameValuePair("salary",String.valueOf(emp.getSalary())));
parameters.add(new BasicNameValuePair("age", String.valueOf(emp.getAge())));
parameters.add(new BasicNameValuePair("gender", emp.getGender()));
HttpEntity entity = new UrlEncodedFormEntity(parameters);
post.setEntity(entity);
HttpResponse resp = client.execute(post);
String result = EntityUtils.toString(resp.getEntity());
return result;

} catch (Exception e) {
e.printStackTrace();
}
return null;
}
protected void onPostExecute(String result) {
listener.onAddFinish(result);
};
}.execute();

}
public static void addEmp2(final Emp emp, final OnAddEmpFinishListener listener) {

new Thread(){
public void run() {
try {
URL url = new URL("http://172.60.50.82:8080/ems/addEmp");
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("POST");
connection.setDoInput(true);
connection.setDoOutput(true);
connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
connection.connect();
OutputStream out = connection.getOutputStream();
PrintWriter pw = new PrintWriter(out,true);
pw.write(getParams(emp));
pw.close();

InputStream in = connection.getInputStream();
BufferedReader br = new BufferedReader(new InputStreamReader(in));
final String result = br.readLine();
br.close();

new Handler(Looper.getMainLooper()).post(new Runnable() {

@Override
public void run() {
listener.onAddFinish(result);
}
});
} catch (Exception e) {
e.printStackTrace();
}
};
}.start();
}

protected static String getParams(Emp emp) {
Map<String , String> map = new HashMap<String, String>();
map.put("name", emp.getName());
map.put("salary", String.valueOf(emp.getSalary()));
map.put("age", String.valueOf(emp.getAge()));
map.put("gender",emp.getGender());
StringBuilder sb = new StringBuilder();
for(Entry<String, String> entry:map.entrySet()){
sb.append(entry.getKey()).append("=").append(entry.getValue()).append("&");
}
return sb.substring(0,sb.length()-1);
}

public static void getAllEmps(final OnLoadEmpsFinishListener listener) {

new AsyncTask<Void, Void, List<Emp>>(){

@Override
protected List<Emp> doInBackground(Void... params) {
try {
HttpClient client = new DefaultHttpClient();
HttpGet get = new HttpGet("http://172.60.50.82:8080/ems/listEmp");
HttpResponse resp = client.execute(get);
HttpEntity entity = resp.getEntity();
String result = EntityUtils.toString(entity);
//Log.d("TAG","emp信息:"+result);
return JsonUtil.getAllEmps(result);

} catch (Exception e) {
e.printStackTrace();
}
return null;
}
protected void onPostExecute(java.util.List<Emp> result) {
listener.onLoadFinish(result);
};
}.execute();
}

public static void getAllEmps2(final OnLoadEmpsFinishListener listener){
new Thread(){
public void run() {
try {
URL url = new URL("http://172.60.50.82:8080/ems/listEmp");
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setDoInput(true);
connection.setRequestMethod("GET");
connection.connect();
InputStream is = connection.getInputStream();
BufferedReader br = new BufferedReader(new InputStreamReader(is));
String line = null;
StringBuilder sb = new StringBuilder();
while((line=br.readLine())!=null){
sb.append(line);
}
br.close();
final List<Emp> emps = JsonUtil.getAllEmps(sb.toString());
new Handler(Looper.getMainLooper()).post(new Runnable() {

@Override
public void run() {
listener.onLoadFinish(emps);
}
});

} catch (Exception e) {
e.printStackTrace();
}
};
}.start();
}
}

4.根据监听器的回调传回的JSON解析结果将数据放到adapter中显示。
@Override
protected void onResume() {
super.onResume();
refresh();
}

private void refresh() {
//真正获取数据源json字符串
biz.getAllEmps(new OnLoadEmpsFinishListener() {

@Override
public void onLoadFinish(List<Emp> emps) {
Log.d("TAG", "员工信息:"+emps.toString());
adapter.addAll(emps, true);
}
});
}
********************************************************
关于Gson解析的使用(使用Volley框架时)
1.下载谷歌官方的jar包,并导入到项目中
2.根据网络访问返回的字符串结果写一个严格一一对应的实体类,并写上set、get以及toString方法
3.在HttpUtil中利用Volley框架发起网络访问并在响应结果监听器回调方法中利用Gson进行网络解析
(利用Volley框架也要先在项目中导入相应的jar包)
实例代码如下:
package com.example.weather.util;

import java.net.URLEncoder;

import android.content.Context;
import android.widget.Toast;

import com.android.volley.RequestQueue;
import com.android.volley.Response.ErrorListener;
import com.android.volley.Response.Listener;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import com.google.gson.Gson;
import com.example.weather.bean.WeatherBean;
import com.example.weather.listener.OnLoadWeatherFinishListener;

public class HttpUtil {

private static RequestQueue queue;

public static void getWeahters(final Context context,String city,final OnLoadWeatherFinishListener listener){
try {
if(queue==null){
queue = Volley.newRequestQueue(context);
}
String encode = URLEncoder.encode(city, "utf8");
String url="http://op.juhe.cn/onebox/weather/query?cityname="+encode+"&key=15b3860417a0875de210d562b0be2ce3";
StringRequest request = new StringRequest(url, new Listener<String>() {

@Override
public void onResponse(String arg0) {
Gson gson = new Gson();
WeatherBean bean = gson.fromJson(arg0, WeatherBean.class);
listener.onLoadFinish(bean);
}
}, new ErrorListener() {

@Override
public void onErrorResponse(VolleyError arg0) {
Toast.makeText(context, arg0.getMessage(), Toast.LENGTH_SHORT).show();
}
});

queue.add(request);
} catch (Exception e) {
e.printStackTrace();
}
}
}
4.通过监听器的回调方法将解析结果传回
**************************************************************
一般解析方式:
JsonObject的解析:
String str="{\"name\":\"zhangsan\“,\"age\":20}";
JSONObject obj=new JSONObject(str);
String name=obj.getString("name");
int age=obj.getInt("age");

JsonArray的解析:
String str="[10,true,\"hello\"]";
JSONArray obj=new JSONArray(str);
String name=obj.getString(2);
int age=obj.getInt(0);

JSON语法

首先看JSON的语法和结构,这样我们才知道怎么去解析它。JSON语法时JavaScript对象表示语法的子集。

JSON的值可以是:

数字(整数或者浮点数)

字符串(在双引号内)

逻辑值(true 或 false)

数组(使用方括号[]包围)

对象( 使用花括号{}包围)

null

JSON中有且只有两种结构:对象和数组。

1、对象:对象在js中表示为“{}”括起来的内容,数据结构为 {key:value,key:value,...}的键值对的结构,在面向对象的语言中,key为对象的属性,value为对应的属性值,所以很容易理解,取值方法为 对象.key 获取属性值,这个属性值的类型可以是 数字、字符串、数组、对象几种。

2、数组:数组在js中是中括号“[]”括起来的内容,数据结构为 ["java","javascript","vb",...],取值方式和所有语言中一样,使用索引获取,字段值的类型可以是 数字、字符串、数组、对象几种。

andoroid解析JSON

android sdk中为我们提供了org.json,可以用来解析json,在android3.0又为在android.util包JsonReader和JsonWriter来进行json的解析和生成。

使用org.json包JSONObject和JSONArray进行解析

我们知道json中就两种结构array和object,因此就有这个两个类进行解析。

如我们有下面几个json字符串:

{"name":"sam","age":18,"weight":60} //json1 一个json对象
[12,13,15]                    //json2 一个数字数组
[{"name":"sam","age":18},{"name":"leo","age":19},{"name":"sky", "age":20}] //json3 json array中有object
第一个json对象json1的解析

JSONObject jsonObj = new JSONObject(json1);
String name = jsonObj.optString("name");
int age = jsonObj.optInt("age");
int weight = jsonObj.optInt("weight");
另外还有

Object opt(String name)
boolean optBoolean(String name)
double optDouble(String name)
JSONArray optJSONArray(String name)
JSONObject optJSONObject(String name)
等方法,我推荐用这些方法,这些方法在解析时,如果对应字段不存在会返回空值或者0,不会报错。

当然如果你使用以下方法

Object get(String name)
boolean getBoolean(String name)
int getInt(String name)
等方法时,代码不会去判断是否存在该字段,需要你自己去判断,否则的话会报错。自己判断的话使用has(String name)来判断。

再来看解析数组,简单的数组。第二个json2

JSONArray jsonArray = new JSONArray(json2);
for (int = 0; i < jsonArray.length();i++) {
    int age = jsonArray.optInt(i); 
}
解析复杂数组,包含对象,json3

JSONArray jsonArray = new JSONArray(json3);
for (int = 0; i < jsonArray.length();i++) {
    JSONObject jsonObject = jsonArray.optJSONObject(i);
    String name = jsonObject.optString("name");
    int age = jsonObject.optInt("age");
}
从上面可以看到数组的话解析方法和对象差不多,只是将键值替换为在数组中的下标。另外也是有optXXX(int index)和getXXX(int index)方法的,opt也是安全的,即对应index无值的时候,不会报错,返回空,推荐使用。

使用JsonReader进行解析

JsonReader的使用其实和xml解析中的pull是有一点类似的,我们来看示例。

前面的JSONObject和JSONArray创建时传的是String,而JsonReader需要传入的时候是Reader,网络访问中,我们可以直接拿输入流传进来,转成Reader。我们这里假设我们上面的String已经转成InputStream了,分别为jsonIs1,jsonIs2,jsonIs3。

上面的json1解析:

JsonReader reader = new JsonReader(new InputStreamReader(jsonIs1));
try {
    reader.beginObject();
    while (reader.hasNext()) {
        String keyName = reader.nextName();
        if (keyName.equals("name")) { 
            String name = reader.nextString();
        } else if (keyName.equals("age")) {
            int age = reader.nextInt();
        } else if (keyName.equals("weight")) {
            int weight = reader.nextInt();
        }
    }
    reader.endObject();
} finally {
    reader.close();
}
上面json2的解析:

JsonReader reader = new JsonReader(new InputStreamReader(jsonIs2));
try {
    List<Integer> ages = new ArrayList<Integer>();
    reader.beginArray();
    while (reader.hasNext()) {
        ages.add(reader.nextInt());
    }
    reader.endArray();
} finally {
    reader.close();
}
第三个我就不写示例了。

看到这个的话是通过去遍历我们的json,去取得我们的内容,我觉得在效率上面会比第一种效率高一些。具体使用的话就按照我这两个例子可以写出来的。
************************************************************************************************
使用GSON解析JSON

GSON是谷歌出品,很好用。同时呢还有一些其他的第三方的比如fastjson等,都和Gson差不多,传一个string和要转换的对象,帮你直接直接解析出来,不再需要我们自己一个字段一段字段的解析。这里就以Gson为例吧,因为我只用过Gson,对其最熟悉。^_^

使用Gson,我们需要导入Gson的包,下载地址https://code.google.com/p/google-gson/downloads/list。

现在开始看看,怎么解析上面的三个json字符串例子。

第一个对象json1

首先我们需要一个实体类

public class People{

public String name;

@SerializedName(age)
pubic int mAge;    //如果我们类中成员的名称和json对象中的键名不同,可以通过注解来设置名字

public int weight;
}
然后就可以解析了

Gson gson = new Gson();
Poeple people = gson.fromJson(json1, People.class);
对于第二个json2,我们可以解析成int数组,也可以解析成Integer的List。 解析成数组:

Gson gson = new Gson();
int[] ages = gson.fromJson(json2, int[].class);
解析成List:

Gson gson = new Gson();
List<Integer> ages = gson.fromJson(json2, new TypeToken<List<Integer>>(){}.getType);
第三个同样可以解析成List或者数组,我们就直接解析成List.

Gson gson = new Gson();
List<People> peoples = gson.fromJson(json3, new TypeToke<List<People>>(){}.getType);
从上面的代码看到,使用Gson解析的话就非常简单了。需要注意的是如果对应的键值和成员名称不同的话可以使用注解来标记。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值