代码改变世界

Android JSON,Gson,fastjson实现比较

2013-11-22 15:09  Andy Ge  阅读(1257)  评论(0编辑  收藏  举报

activity_main.xml

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:orientation="vertical" >

    <TableLayout
        android:layout_width="wrap_content"
        android:layout_height="match_parent" >

        <TableRow>

            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="org.json" />

            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="fastjson" />

            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="gson" />
        </TableRow>

        <TableRow>

            <LinearLayout
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:orientation="vertical" >

                <Button
                    android:id="@+id/person"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:onClick="click"
                    android:text="person" />

                <Button
                    android:id="@+id/persons"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:onClick="click"
                    android:text="persons" />

                <Button
                    android:id="@+id/stringList"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:onClick="click"
                    android:text="stringList" />

                <Button
                    android:id="@+id/listMap"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:onClick="click"
                    android:text="listMap" />

                <Button
                    android:id="@+id/raw"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:onClick="click"
                    android:text="Self" />
            </LinearLayout>

            <LinearLayout
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:orientation="vertical" >

                <Button
                    android:id="@+id/person2"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:onClick="click"
                    android:text="person" />

                <Button
                    android:id="@+id/persons2"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:onClick="click"
                    android:text="persons" />

                <Button
                    android:id="@+id/stringList2"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:onClick="click"
                    android:text="stringList" />

                <Button
                    android:id="@+id/listMap2"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:onClick="click"
                    android:text="listMap" />

                <Button
                    android:id="@+id/raw2"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:onClick="click"
                    android:text="Self" />
            </LinearLayout>

            <LinearLayout
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:orientation="vertical" >

                <Button
                    android:id="@+id/person3"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:onClick="click"
                    android:text="person" />

                <Button
                    android:id="@+id/persons3"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:onClick="click"
                    android:text="persons" />

                <Button
                    android:id="@+id/stringList3"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:onClick="click"
                    android:text="stringList" />

                <Button
                    android:id="@+id/listMap3"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:onClick="click"
                    android:text="listMap" />

                <Button
                    android:id="@+id/raw3"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:onClick="click"
                    android:text="Self" />
            </LinearLayout>
        </TableRow>
    </TableLayout>

    <Button
        android:id="@+id/rawString"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:onClick="click"
        android:text="RawString" />

    <TextView
        android:id="@+id/tvShow"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/hello_world" />

</LinearLayout>

Manifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.netjson"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk
        android:minSdkVersion="8"
        android:targetSdkVersion="17" />

    <uses-permission android:name="android.permission.INTERNET" />

    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name="com.example.netjson.MainActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>
MainActivity.java

package com.example.netjson;

import java.io.InputStream;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

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

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;

import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.app.Activity;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.widget.TextView;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

public class MainActivity extends Activity {

    String PATH = "http://192.168.0.102:7020/JSON.aspx";
    String TAG = "JSON";
    TextView tvShow;
    Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
            case 0x123:
                tvShow.setText(msg.obj.toString());
                Log.i(TAG, msg.obj.toString());
                break;
            }
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        tvShow = (TextView) findViewById(R.id.tvShow);
    }

    public void click(final View v) {
        final int vId = v.getId();
        new Thread() {
            public void run() {
                asynCall(vId);
            }
        }.start();
    }

    private void asynCall(int viewId) {
        String jsonStr = "";
        switch (viewId) {
        case R.id.person:
            String path1 = PATH + "?action_flag=person";
            String jsonString1 = HTTPUtils.getJsonContent(path1);
            Person person = JSONTool.getPerson(jsonString1);
            jsonStr = person.toString();
            break;
        case R.id.persons:
            String path2 = PATH + "?action_flag=persons";
            String jsonString2 = HTTPUtils.getJsonContent(path2);
            List<Person> list2 = JSONTool.getPersons(jsonString2);
            jsonStr = list2.toString();
            break;
        case R.id.stringList:
            String path3 = PATH + "?action_flag=stringList";
            String jsonString3 = HTTPUtils.getJsonContent(path3);
            List<String> list3 = JSONTool.getList(jsonString3);
            jsonStr = list3.toString();
            break;
        case R.id.listMap:
            String path4 = PATH + "?action_flag=listMap";
            String jsonString4 = HTTPUtils.getJsonContent(path4);
            List<Map<String, Object>> list4 = JSONTool.getListMap(jsonString4);
            jsonStr = list4.toString();
            break;
        case R.id.raw:
            List<Map<String, Object>> list = getListMap();

            JSONObject jo = new JSONObject();
            try {
                jo.put("list", list);
            } catch (JSONException e1) {
                // TODO Auto-generated catch block
                e1.printStackTrace();
            }
            String jStr = jo.toString();
            list.clear();
            try {
                JSONObject jsonObject = new JSONObject(jStr);
                JSONArray jsonArray = jsonObject.getJSONArray("list");
                for (int i = 0; i < jsonArray.length(); i++) {
                    JSONObject jsonObject2 = jsonArray.getJSONObject(i);
                    Map<String, Object> map = new HashMap<String, Object>();
                    Iterator<String> iterator = jsonObject2.keys();
                    while (iterator.hasNext()) {
                        String json_key = iterator.next();
                        Object json_value = jsonObject2.get(json_key);
                        if (json_value == null) {
                            json_value = "";
                        }
                        map.put(json_key, json_value);
                    }
                    list.add(map);
                }
            } catch (JSONException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            jsonStr = list.toString();
            break;
        case R.id.person2:
            String path21 = PATH + "?action_flag=person";
            String jsonString21 = HTTPUtils.getJsonContent(path21);
            Person person2 = FastJsonTools
                    .getPerson(jsonString21, Person.class);
            jsonStr = person2.toString();
            break;
        case R.id.persons2:
            String path22 = PATH + "?action_flag=persons";
            String jsonString22 = HTTPUtils.getJsonContent(path22);
            List<Person> list22 = FastJsonTools.getPersons(jsonString22,
                    Person.class);
            jsonStr = list22.toString();
            break;
        case R.id.stringList2:
            String path23 = PATH + "?action_flag=stringList";
            String jsonString23 = HTTPUtils.getJsonContent(path23);
            List<String> list23 = FastJsonTools.getPersons(jsonString23,
                    String.class);
            jsonStr = list23.toString();
            break;
        case R.id.listMap2:
            String path24 = PATH + "?action_flag=listMap";
            String jsonString24 = HTTPUtils.getJsonContent(path24);
            List<Map<String, Object>> list24 = FastJsonTools
                    .getListMap(jsonString24);
            jsonStr = list24.toString();
            break;
        case R.id.raw2:
            List<Map<String, Object>> listt = getListMap();

            String jStrt = JSON.toJSONString(listt);
            List<Map<String, Object>> l = JSON.parseObject(jStrt,
                    new TypeReference<List<Map<String, Object>>>() {
                    });
            jsonStr = l.toString();
            break;
        case R.id.person3:
            String path31 = PATH + "?action_flag=person";
            String jsonString31 = HTTPUtils.getJsonContent(path31);
            Person person3 = GsonTools.getPerson(jsonString31, Person.class);
            jsonStr = person3.toString();
            break;
        case R.id.persons3:
            String path32 = PATH + "?action_flag=persons";
            String jsonString32 = HTTPUtils.getJsonContent(path32);
            List<Person> list32 = GsonTools.getPersons(jsonString32,
                    Person.class);
            jsonStr = list32.toString();
            break;
        case R.id.stringList3:
            String path33 = PATH + "?action_flag=stringList";
            String jsonString33 = HTTPUtils.getJsonContent(path33);
            List<String> list33 = GsonTools.getList(jsonString33);
            jsonStr = list33.toString();
            break;
        case R.id.listMap3:
            String path34 = PATH + "?action_flag=listMap";
            String jsonString34 = HTTPUtils.getJsonContent(path34);
            List<Map<String, Object>> list34 = GsonTools
                    .listKeyMaps(jsonString34);
            jsonStr = list34.toString();
            break;
        case R.id.raw3:
            List<Map<String, Object>> listg = getListMap();

            Gson gson = new Gson();
            String jStrg = gson.toJson(listg);
            listg.clear();
            try {
                listg = gson.fromJson(jStrg,
                        new TypeToken<List<Map<String, Object>>>() {
                        }.getType());
            } catch (Exception e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            jsonStr = listg.toString();
            break;
        case R.id.rawString:
            String x;
            JSONObject obj;
            try {
                InputStream is = this.getResources()
                        .openRawResource(R.raw.json);
                byte[] buffer = new byte[is.available()];
                is.read(buffer);
                String json = new String(buffer, "utf-8");
                obj = new JSONObject(json);
                StringBuilder sb = new StringBuilder();

                x = obj.getString("姓名");
                sb.append("======姓名========\n" + x);
                x = obj.getString("性别");
                sb.append("\n======性别========\n" + x);
                x = obj.getString("年龄");
                sb.append("\n======年龄========\n" + x);

                JSONObject obj1 = obj.getJSONObject("学习成绩");
                x = obj1.getString("数学");
                sb.append("\n======数学========\n" + x);
                x = obj1.getString("语文");
                sb.append("\n======语文========\n" + x);
                x = obj1.getString("英语");
                sb.append("\n======英语========\n" + x);

                JSONArray array = obj1.getJSONArray("综合");
                obj = array.getJSONObject(0);
                x = obj.getString("文科综合");
                sb.append("\n======文科综合========\n" + x);
                obj = array.getJSONObject(1);
                x = obj.getString("理科综合");
                sb.append("\n======理科综合========\n" + x);

                JSONStringer s = new JSONStringer();
                sb.append("\n======================\n"
                        + s.object().key("a").value("aaa").endObject()
                                .toString());
                jsonStr = sb.toString();
            } catch (Exception e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }

            break;
        }
        Message msg = new Message();
        msg.what = 0x123;
        msg.obj = jsonStr;
        handler.sendMessage(msg);
    }

    private List<Map<String, Object>> getListMap() {
        List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
        Map<String, Object> map1 = new HashMap<String, Object>();
        map1.put("Id", 1001);
        map1.put("name", "jack");
        map1.put("address", "beijing");
        Map<String, Object> map2 = new HashMap<String, Object>();
        map2.put("id", 1002);
        map2.put("name", "rose");
        map2.put("address", "shanghai");
//        map2.put("Married", false);
//        map2.put("Birthday", new Date());
        list.add(map1);
        list.add(map2);
        return list;
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }

}

Person.java

package com.example.netjson;

public class Person {
    private int id;
    private String name;
    private String address;

    public Person() {
        super();
    }

    public Person(int id, String name, String addrss) {
        super();
        this.id = id;
        this.name = name;
        this.address = addrss;
    }

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getAddress() {
        return address;
    }

    public void setAddress(String address) {
        this.address = address;
    }

    @Override
    public String toString() {
        return "Person [addrss=" + address + ", id=" + id + ", name=" + name
                + "]";
    }
}

HTTPUtils.java

package com.example.netjson;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

public class HTTPUtils {

    public HTTPUtils() {
    }

    public static String getJsonContent(String path) {
        try {
            URL url = new URL(path);
            HttpURLConnection connection = (HttpURLConnection) url
                    .openConnection();
            connection.setConnectTimeout(30000);
            connection.setRequestMethod("GET");
            connection.setDoInput(true);
            int code = connection.getResponseCode();
            if (code == 200) {
                return changeInputStream(connection.getInputStream());
            }
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 将一个输入流转换成指定编码的字符串
     * 
     * @param inputStream
     * @return
     */
    private static String changeInputStream(InputStream inputStream) {
        String jsonString = "";
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        int len = 0;
        byte[] data = new byte[1024];
        try {
            while ((len = inputStream.read(data)) != -1) {
                outputStream.write(data, 0, len);
            }
            jsonString = new String(outputStream.toByteArray());
        } catch (IOException e) {
            e.printStackTrace();
        } 
        return jsonString;
    }
}

JOSNTool.java

package com.example.netjson;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

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

/**
 * 完成对JSON数据的解析
 * 
 * @author wulianghuan
 * 
 */
public class JSONTool {

    public JSONTool() {

    }

    public static String createjsonString(String key, Object value) {
        JSONObject jsonObject = new JSONObject();
        try {
            jsonObject.put(key, value);
        } catch (JSONException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return jsonObject.toString();
    }

    /**
     * 获取对象数据
     * 
     * @param key
     * @param jsonString
     * @return
     */
    public static Person getPerson(String jsonString) {
        Person person = new Person();
        try {
            JSONObject personObject = new JSONObject(jsonString);
            person.setId(personObject.getInt("id"));
            person.setName(personObject.getString("name"));
            person.setAddress(personObject.getString("address"));
        } catch (JSONException e) {
            e.printStackTrace();
        }
        return person;
    }

    /**
     * 获取对象数组数据
     * 
     * @param key
     * @param jsonString
     * @return
     */
    public static List<Person> getPersons(String jsonString) {
        List<Person> list = new ArrayList<Person>();
        try {
            JSONArray jsonArray = new JSONArray(jsonString);
            // 返回json的数组
            for (int i = 0; i < jsonArray.length(); i++) {
                JSONObject jsonObject2 = jsonArray.getJSONObject(i);
                Person person = new Person();
                person.setId(jsonObject2.getInt("id"));
                person.setName(jsonObject2.getString("name"));
                person.setAddress(jsonObject2.getString("address"));
                list.add(person);
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }

        return list;
    }

    /**
     * 获取String数组数据
     * 
     * @param key
     * @param jsonString
     * @return
     */
    public static List<String> getList(String jsonString) {
        List<String> list = new ArrayList<String>();
        try {
            JSONArray jsonArray = new JSONArray(jsonString);
            for (int i = 0; i < jsonArray.length(); i++) {
                String msg = jsonArray.getString(i);
                list.add(msg);
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
        return list;
    }

    /**
     * 获取对象的Map集合数据
     * 
     * @param key
     * @param jsonString
     * @return
     */
    public static List<Map<String, Object>> getListMap(String jsonString) {
        List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
        try {
            JSONArray jsonArray = new JSONArray(jsonString);
            for (int i = 0; i < jsonArray.length(); i++) {
                JSONObject jsonObject2 = jsonArray.getJSONObject(i);
                Map<String, Object> map = new HashMap<String, Object>();
                Iterator<String> iterator = jsonObject2.keys();
                while (iterator.hasNext()) {
                    String json_key = iterator.next();
                    Object json_value = jsonObject2.get(json_key);
                    if (json_value == null) {
                        json_value = "";
                    }
                    map.put(json_key, json_value);
                }
                list.add(map);
            }
        } catch (JSONException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        return list;
    }
}

FastJsonTool.java

package com.example.netjson;

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

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;

public class FastJsonTools {

    public FastJsonTools() {
        // TODO Auto-generated constructor stub
    }

    /**
     * @param <T>
     * @param jsonString
     * @param cls
     * @return
     */
    public static <T> T getPerson(String jsonString, Class<T> cls) {
        T t = null;
        try {
            t = JSON.parseObject(jsonString, cls);
        } catch (Exception e) {
            e.printStackTrace();
            // TODO: handle exception
        }
        return t;
    }

    /**
     * 使用Gson进行解析 List<Person>
     * 
     * @param <T>
     * @param jsonString
     * @param cls
     * @return
     */
    public static <T> List<T> getPersons(String jsonString, Class<T> cls) {
        List<T> list = new ArrayList<T>();
        try {
            list = JSON.parseArray(jsonString, cls);
        } catch (Exception e) {
        }
        return list;
    }

    public static List<Map<String, Object>> getListMap(String jsonString) {
        List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
        try {
            list = JSON.parseObject(jsonString,
                    new TypeReference<List<Map<String, Object>>>() {
                    });
        } catch (Exception e) {
            e.printStackTrace();
        }
        return list;
    }
}

GsonTool.java

package com.example.netjson;

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

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

;
public class GsonTools {

    public GsonTools() {
        // TODO Auto-generated constructor stub
    }

    /**
     * @param <T>
     * @param jsonString
     * @param cls
     * @return
     */
    public static <T> T getPerson(String jsonString, Class<T> cls) {
        T t = null;
        try {
            Gson gson = new Gson();
            t = gson.fromJson(jsonString, cls);
        } catch (Exception e) {
            // TODO: handle exception
        }
        return t;
    }

    /**
     * 使用Gson进行解析 List<Person>
     * 
     * @param <T>
     * @param jsonString
     * @param cls
     * @return
     */
    public static <T> List<T> getPersons(String jsonString, Class<T> cls) {
        List<T> list = new ArrayList<T>();
        try {
            Gson gson = new Gson();
            list = gson.fromJson(jsonString, new TypeToken<List<T>>() {
            }.getType());
        } catch (Exception e) {
        }
        return list;
    }

    /**
     * @param jsonString
     * @return
     */
    public static List<String> getList(String jsonString) {
        List<String> list = new ArrayList<String>();
        try {
            Gson gson = new Gson();
            list = gson.fromJson(jsonString, new TypeToken<List<String>>() {
            }.getType());
        } catch (Exception e) {
            // TODO: handle exception
        }
        return list;
    }

    public static List<Map<String, Object>> listKeyMaps(String jsonString) {
        List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
        try {
            Gson gson = new Gson();
            list = gson.fromJson(jsonString,
                    new TypeToken<List<Map<String, Object>>>() {
                    }.getType());
        } catch (Exception e) {
            // TODO: handle exception
        }
        return list;
    }
}