最近做一项目,有很多地方得用到网络数据传输与解析,这里采用的是Json方式,它与传统的XML解析方式比起来,有自己的一些优点,首先,它是比XML更轻量级,再一个,写一个XML文件是个烦人的事儿,而Json则相对轻松些。
Android平台有Jsong相关的类来进行Json数据解析,悲剧的是,它们是Android SDK3.0以后才能用的。不过在谷歌网站: http://code.google.com/p/google-gson/里有一个名为Gson的类库,可以用它来解析Json数据,并且,Adroid 3.0平台里其实也就是把这一部分直接整合进Android里了。我们要解析Json数据,直接去网站上下载个jar包,导入到工程里,就可以解析Json数据了。
下面有个例子,很清晰的解释了这种工作方式:
先看看两个我自己封装的类:
HttpUtils.java:
public class HttpUtils { //从服务器端下载到Json数据,也就是个字符串public static String getData(String url) throws Exception {StringBuilder sb = new StringBuilder();
HttpClient httpClient = new DefaultHttpClient();
HttpGet httpGet = new HttpGet(url);
HttpResponse httpResponse = httpClient.execute(httpGet);HttpEntity httpEntity = httpResponse.getEntity();if (httpEntity != null) {InputStream instream = httpEntity.getContent();BufferedReader reader = new BufferedReader(new InputStreamReader(instream));String line = null;
while ((line = reader.readLine()) != null) {sb.append(line);}return sb.toString();
}return null;}JsonUtils.java:public class JsonUtils {public static List<Student> parseStudentFromJson(String data) {Type listType = new TypeToken<LinkedList<Student>>() {
}.getType();Gson gson = new Gson();
LinkedList<Student> list = gson.fromJson(data, listType);return list;
}}里面的Student是一个JavaBean对象:
public class Student {private String name;
private int age;private String id;
public Student() {
super();}public Student(String name, int age, String id) {super();this.name = name;
this.age = age;
this.id = id;
}public String getName() {
return name;
}public void setName(String name) {this.name = name;
}public int getAge() {return age;
}public void setAge(int age) {this.age = age;
}public String getId() {
return id;
}public void setId(String id) {this.id = id;
}}再看看我们要解析网络数据的Activity:
public class MainActivity extends Activity {private TextView textView;
private List<Student> list;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.main);textView = (TextView) findViewById(R.id.textView);String data = null;
try {
data = HttpUtils.getData("http://10.16.12.165:8080/JsonTest/JsonTestServlet");
} catch (Exception e) {
e.printStackTrace();}String result = "";
list = JsonUtils.parseStudentFromJson(data);for (Student s : list) {
result += "name: " + s.getName() + " " + "age: " + s.getAge()+ " " + "id: " + s.getId() + "\n";}textView.setText(result);}}这样就可以获取网络数据并加以解析利用了,运行结果如下:
另外,还有一篇不错的文章: http://curran.blog.51cto.com/blog/2788306/514605