android Json Gson FastJson 解析

Posted 每天进步一点点!

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了android Json Gson FastJson 解析相关的知识,希望对你有一定的参考价值。

一 Json 

  xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical" android:layout_width="fill_parent"
    android:layout_height="fill_parent">
    <Button android:id="@+id/person" android:layout_width="fill_parent"
        android:layout_height="wrap_content" android:text="解析Person数据" />
    <Button android:id="@+id/persons" android:layout_width="fill_parent"
        android:layout_height="wrap_content" android:text="解析List嵌套Person数据" />
    <Button android:id="@+id/liststring" android:layout_width="fill_parent"
        android:layout_height="wrap_content" android:text="解析List嵌套String数据" />
    <Button android:id="@+id/listmap" android:layout_width="fill_parent"
        android:layout_height="wrap_content" android:text="解析ListMap数据" />
</LinearLayout>

 java 

  Main.java

 

package com.android.myjson;

import java.util.List;
import java.util.Map;

import com.android.myjson.domain.Person;
import com.android.myjson.http.HttpUtils;
import com.android.myjson.json.JsonTools;

import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;

public class Main extends Activity implements OnClickListener {
    /** Called when the activity is first created. */
    private Button person, persons, liststring, listmap;
    private static final String TAG = "Main";

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        person = (Button) this.findViewById(R.id.person);
        persons = (Button) this.findViewById(R.id.persons);
        liststring = (Button) this.findViewById(R.id.liststring);
        listmap = (Button) this.findViewById(R.id.listmap);
        person.setOnClickListener(this);
        persons.setOnClickListener(this);
        liststring.setOnClickListener(this);
        listmap.setOnClickListener(this);

    }

    @Override
    public void onClick(View v) {
        // TODO Auto-generated method stub
        switch (v.getId()) {
        case R.id.person:
            String path = "http://192.168.11.249:8080/jsonProject/servlet/JsonAction?action_flag=person";
            String jsonString = HttpUtils.getJsonContent(path);
            Person person = JsonTools.getPerson("person", jsonString);
            Log.i(TAG, person.toString());
            break;
        case R.id.persons:
            String path2 = "http://192.168.11.249:8080/jsonProject/servlet/JsonAction?action_flag=persons";
            String jsonString2 = HttpUtils.getJsonContent(path2);
            List<Person> list2 = JsonTools.getPersons("persons", jsonString2);
            Log.i(TAG, list2.toString());
            break;
        case R.id.liststring:
            String path3 = "http://192.168.11.249:8080/jsonProject/servlet/JsonAction?action_flag=liststring";
            String jsonString3 = HttpUtils.getJsonContent(path3);
            List<String> list3 = JsonTools.getList("liststring", jsonString3);
            Log.i(TAG, list3.toString());
            break;
        case R.id.listmap:
            String path4 = "http://192.168.11.249:8080/jsonProject/servlet/JsonAction?action_flag=listmap";
            String jsonString4 = HttpUtils.getJsonContent(path4);
            List<Map<String, Object>> list4 = JsonTools.listKeyMaps("listmap",
                    jsonString4);
            Log.i(TAG, list4.toString());
            break;
        }
    }
}

  Person.java

 1 package com.android.myjson.domain;
 2 
 3 public class Person {
 4 
 5     private int id;
 6     private String name;
 7 
 8     public Person(int id, String name, String address) {
 9         super();
10         this.id = id;
11         this.name = name;
12         this.address = address;
13     }
14 
15     private String address;
16 
17     public int getId() {
18         return id;
19     }
20 
21     @Override
22     public String toString() {
23         return "Person [address=" + address + ", id=" + id + ", name=" + name
24                 + "]";
25     }
26 
27     public void setId(int id) {
28         this.id = id;
29     }
30 
31     public String getName() {
32         return name;
33     }
34 
35     public void setName(String name) {
36         this.name = name;
37     }
38 
39     public String getAddress() {
40         return address;
41     }
42 
43     public void setAddress(String address) {
44         this.address = address;
45     }
46 
47     public Person() {
48         // TODO Auto-generated constructor stub
49     }
50 
51 }
View Code

 HttpUtils.java

 1 package com.android.myjson.http;
 2 
 3 import java.io.ByteArrayOutputStream;
 4 import java.io.IOException;
 5 import java.io.InputStream;
 6 import java.net.HttpURLConnection;
 7 import java.net.URL;
 8 
 9 public class HttpUtils {
10 
11     public HttpUtils() {
12         // TODO Auto-generated constructor stub
13     }
14 
15     public static String getJsonContent(String url_path) {
16         try {
17             URL url = new URL(url_path);
18             HttpURLConnection connection = (HttpURLConnection) url
19                     .openConnection();
20             connection.setConnectTimeout(3000);
21             connection.setRequestMethod("GET");
22             connection.setDoInput(true);
23             int code = connection.getResponseCode();
24             if (code == 200) {
25                 return changeInputStream(connection.getInputStream());
26             }
27         } catch (Exception e) {
28             // TODO: handle exception
29         }
30         return "";
31     }
32 
33     private static String changeInputStream(InputStream inputStream) {
34         // TODO Auto-generated method stub
35         String jsonString = "";
36         ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
37         int len = 0;
38         byte[] data = new byte[1024];
39         try {
40             while ((len = inputStream.read(data)) != -1) {
41                 outputStream.write(data, 0, len);
42             }
43             jsonString = new String(outputStream.toByteArray());
44         } catch (IOException e) {
45             // TODO Auto-generated catch block
46             e.printStackTrace();
47         }
48         return jsonString;
49     }
50 }
View Code

JsonTools.java

  1 package com.android.myjson.json;
  2 
  3 import java.util.ArrayList;
  4 import java.util.HashMap;
  5 import java.util.Iterator;
  6 import java.util.List;
  7 import java.util.Map;
  8 
  9 import org.json.JSONArray;
 10 import org.json.JSONObject;
 11 
 12 import com.android.myjson.domain.Person;
 13 
 14 /**
 15  * 完成对json数据的解析
 16  * 
 17  * @author jack
 18  * 
 19  */
 20 public class JsonTools {
 21 
 22     public JsonTools() {
 23         // TODO Auto-generated constructor stub
 24     }
 25 
 26     public static Person getPerson(String key, String jsonString) {
 27         Person person = new Person();
 28         try {
 29             JSONObject jsonObject = new JSONObject(jsonString);
 30             JSONObject personObject = jsonObject.getJSONObject("person");
 31             person.setId(personObject.getInt("id"));
 32             person.setName(personObject.getString("name"));
 33             person.setAddress(personObject.getString("address"));
 34         } catch (Exception e) {
 35             // TODO: handle exception
 36         }
 37         return person;
 38     }
 39 
 40     public static List<Person> getPersons(String key, String jsonString) {
 41         List<Person> list = new ArrayList<Person>();
 42         try {
 43             JSONObject jsonObject = new JSONObject(jsonString);
 44             // 返回json的数组
 45             JSONArray jsonArray = jsonObject.getJSONArray(key);
 46             for (int i = 0; i < jsonArray.length(); i++) {
 47                 JSONObject jsonObject2 = jsonArray.getJSONObject(i);
 48                 Person person = new Person();
 49                 person.setId(jsonObject2.getInt("id"));
 50                 person.setName(jsonObject2.getString("name"));
 51                 person.setAddress(jsonObject2.getString("address"));
 52                 list.add(person);
 53             }
 54         } catch (Exception e) {
 55             // TODO: handle exception
 56         }
 57         return list;
 58     }
 59 
 60     public static List<String> getList(String key, String jsonString) {
 61         List<String> list = new ArrayList<String>();
 62         try {
 63             JSONObject jsonObject = new JSONObject(jsonString);
 64             JSONArray jsonArray = jsonObject.getJSONArray(key);
 65             for (int i = 0; i < jsonArray.length(); i++) {
 66                 String msg = jsonArray.getString(i);
 67                 list.add(msg);
 68             }
 69         } catch (Exception e) {
 70             // TODO: handle exception
 71         }
 72         return list;
 73     }
 74 
 75     public static List<Map<String, Object>> listKeyMaps(String key,
 76             String jsonString) {
 77         List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
 78         try {
 79             JSONObject jsonObject = new JSONObject(jsonString);
 80             JSONArray jsonArray = jsonObject.getJSONArray(key);
 81             for (int i = 0; i < jsonArray.length(); i++) {
 82                 JSONObject jsonObject2 = jsonArray.getJSONObject(i);
 83                 Map<String, Object> map = new HashMap<String, Object>();
 84                 Iterator<String> iterator = jsonObject2.keys();
 85                 while (iterator.hasNext()) {
 86                     String json_key = iterator.next();
 87                     Object json_value = jsonObject2.get(json_key);
 88                     if (json_value == null) {
 89                         json_value = "";
 90                     }
 91                     map.put(json_key, json_value);
 92                 }
 93                 list.add(map);
 94             }
 95         } catch (Exception e) {
 96             // TODO: handle exception
 97         }
 98         return list;
 99     }
100 }
View Code

 

以上是关于android Json Gson FastJson 解析的主要内容,如果未能解决你的问题,请参考以下文章

android 怎么添加gson

Android Gson解析json工具类封装

android开发笔记之Gson解析

Android--------使用gson解析json文件

Android解析json-Gson使用

android中gson解析怎样防止参数确实