代码改变世界

ANDROID与.Net之间JSON实践

2013-11-20 14:28  Andy Ge  阅读(495)  评论(0编辑  收藏  举报

Asp.Net端:

JsonHelper.cs

using System.Runtime.Serialization.Json;
using System.IO;
using System.Text;

namespace NetJSON
{
    /// <summary>
    /// JSON序列化和反序列化辅助类
    /// </summary>
    public class JsonHelper
    {
        /// <summary>
        /// JSON序列化
        /// </summary>
        public static string JsonSerializer<T>(T t)
        {
            DataContractJsonSerializer ser = new DataContractJsonSerializer(typeof(T));
            MemoryStream ms = new MemoryStream();
            ser.WriteObject(ms, t);
            string jsonString = Encoding.UTF8.GetString(ms.ToArray());
            ms.Close();
            return jsonString;
        }

        /// <summary>
        /// JSON反序列化
        /// </summary>
        public static T JsonDeserialize<T>(string jsonString)
        {
            DataContractJsonSerializer ser = new DataContractJsonSerializer(typeof(T));
            MemoryStream ms = new MemoryStream(Encoding.UTF8.GetBytes(jsonString));
            T obj = (T)ser.ReadObject(ms);
            return obj;
        }
    }
}

JSON.aspx.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Collections;

namespace NetJSON
{
    public partial class JSON : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            string flag = Request["action_flag"];
            string jsonStr = "";
            switch (flag)
            {
                case "person":
                    var p = new Person();
                    p.Id = 100;
                    p.Name = "张三";
                    p.Address = "北京朝阳";
                    jsonStr = JsonHelper.JsonSerializer<Person>(p);
                    break;
                case "persons":
                    List<Person> persons = new List<Person>();
                    persons.Add(new Person
                    {
                        Id = 101,
                        Name = "李四",
                        Address = "北京昌平"
                    });
                    persons.Add(new Person
                    {
                        Id = 102,
                        Name = "王五",
                        Address = "北京顺义"
                    });
                    persons.Add(new Person
                    {
                        Id = 103,
                        Name = "赵六",
                        Address = "天津南开"
                    });
                    jsonStr = JsonHelper.JsonSerializer<List<Person>>(persons);
                    break;
                case "stringList":
                    List<string> strs = new List<string>();
                    strs.Add("china");
                    strs.Add("beijing");
                    strs.Add("chaoyang");
                    jsonStr = JsonHelper.JsonSerializer<List<string>>(strs);
                    break;
                case "listMap":
                    List<Hashtable> listMap = new List<Hashtable>();
                    Hashtable ht = new Hashtable();
                    ht.Add("Id", 203);
                    ht.Add("Name", "老赵");
                    ht.Add("Age", 36);
                    listMap.Add(ht);
                    ht = new Hashtable();
                    ht.Add("Id", 204);
                    ht.Add("Name", "老张");
                    ht.Add("Age", 46);
                    ht.Add("Married", true);
                    listMap.Add(ht);

                    List<SortedDictionary<string, object>> list = new List<SortedDictionary<string, object>>();
                    SortedDictionary<string, object> dict = new SortedDictionary<string, object>();
                    dict.Add("Id", 334);
                    dict.Add("Name", "XYZ");
                    list.Add(dict);
                    dict = new SortedDictionary<string, object>();
                    dict.Add("Id", 334);
                    dict.Add("Address", "XYZ");
                    dict.Add("Married", false);
                    list.Add(dict);
                    jsonStr = JsonHelper.JsonSerializer<List<SortedDictionary<string, object>>>(list);
                    break;
            }
            Response.Write(jsonStr);
            Response.End();
        }
    }

    public class Person
    {
        public int Id { get; set; }
        public string Name { get; set; }
        public string Address { get; set; }
    }
}

返回的JSON结果:

person:

{"Address":"北京朝阳","Id":100,"Name":"张三"}

persons:

[{"Address":"北京昌平","Id":101,"Name":"李四"},{"Address":"北京顺义","Id":102,"Name":"王五"},{"Address":"天津南开","Id":103,"Name":"赵六"}]

stringList:

["china","beijing","chaoyang"]

listMap:

[[{"Key":"Id","Value":201},{"Key":"Name","Value":"老赵"}],[{"Key":"Id","Value":203},{"Key":"Birthday","Value":"\/Date(232214400000+0800)\/"},{"Key":"Married","Value":true}]]

 

Android端:

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
                + "]";
    }
}

JSONTool.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 jsonObject = new JSONObject(jsonString);
            JSONObject personObject = jsonObject.getJSONObject(key);
            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++) {
                JSONArray jsonArray2 = jsonArray.getJSONArray(i);
                Map<String, Object> tmpMap = new HashMap<String, Object>();
                for (int j = 0; j < jsonArray2.length(); j++) {
                    Map<String, Object> map = new HashMap<String, Object>();
                    JSONObject jsonObject2 = jsonArray2.getJSONObject(j);
                    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);
                    }
                    tmpMap.put(map.get("Key").toString(), map.get("Value"));
                }
                list.add(tmpMap);
            }
        } catch (JSONException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        return list;
    }
}

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;
    }
}

activity_main.xml

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context=".MainActivity" >

    <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" />

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

</RelativeLayout>

MainActivity.java

package com.example.netjson;

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

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;

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());
                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;
        }
        Message msg = new Message();
        msg.what = 0x123;
        msg.obj = jsonStr;
        handler.sendMessage(msg);
    }

    @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;
    }

}

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>

输出结果:

Person [addrss=北京朝阳, id=100, name=张三]
[Person [addrss=北京昌平, id=101, name=李四], Person [addrss=北京顺义, id=102, name=王五], Person [addrss=天津南开, id=103, name=赵六]]
[china, beijing, chaoyang]
[{Name=老赵, Id=201}, {Married=true, Birthday=/Date(232214400000+0800)/, Id=203}]