ANDROID与.Net之间JSON实践
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}]
ANDROID与.Net之间JSON实践的更多相关文章
- Android和PHP开发最佳实践
Android和PHP开发最佳实践 <Android和PHP开发最佳实践>基本信息作者: 黄隽实丛书名: 移动应用开发技术丛书出版社:机械工业出版社ISBN:9787111410508上架 ...
- 美团外卖Android平台化的复用实践
美团外卖平台化复用主要是指多端代码复用,正如美团外卖iOS多端复用的推动.支撑与思考文章所述,多端包含有两层意思:其一是相同业务的多入口,指美团外卖业务需要在美团外卖App(下文简称外卖App)和美团 ...
- Google Developing for Android 三 - Performance最佳实践
Google Developing for Android 三 - Performance最佳实践 发表于 2015-06-07 | 分类于 Android最佳实践 原文 Developing ...
- Google Developing for Android 二 - Memory 最佳实践 // lightSky‘Blog
Google Developing for Android 二 - Memory 最佳实践 | 分类于 Android最佳实践 原文:Developing for Android, II Th ...
- Android之Activity之间跳转
本人自学Android,想到什么就写点什么.主要是怕忘了,哈哈~请观者不要建议~ 今天写点Android窗口之间的跳转以及自己理解: 1.Android中窗口之间的跳转,就是Activity之间的跳转 ...
- Android 6.0 源代码编译实践
http://www.judymax.com/archives/1087 Android 6.0 源代码编译实践 https://mirrors.tuna.tsinghua.edu.cn/help/A ...
- 深入分析:Android中app之间的交互(二,使用ComponentName)
在前一篇相关主题的博文中我们了解了如何使用Action来启动当前应用之外的Activity处理我们的业务逻辑,在本篇笔记中我在简单介绍一下使用ComponentName来与当前应用之外的应用进行交互. ...
- IntelliJ IDEA:Getting Started with Spring MVC, Hibernate and JSON实践
原文:IntelliJ IDEA:Getting Started with Spring MVC, Hibernate and JSON实践 最近把编辑器换成IntelliJ IDEA,主要是Ecli ...
- Android 和 PHP 之间进行数据加密传输
Android 和 PHP 之间进行数据加密传输 [代码] [Java]代码 1 mcrypt = new MCrypt(); 2 /* Encrypt */ 3 String encrypted = ...
随机推荐
- AFNetworking (3.1.0) 源码解析 <六>
这次继续介绍文件夹Serialization下的类AFURLResponseSerialization.这次介绍就不拆分了,整体来看一下.h和.m文件. 协议AFURLResponseSerializ ...
- 《HTML5 从入门到精通--7.6.3 单元格垂直跨度——rowspan》
单元格除了能够在水平方向上跨列,还能够垂直方向上跨行.跨行设置须要使用rowspan參数. 语法 <td rowspan="单元格跨行数"> 语法解释 与水平跨度相相应 ...
- php做站点购物车 你搞懂了吗?
网上购物现已成为时尚,客户选择一个商品将其放入到购物车,然后返回继续购物或者去收银台,这个功能怎样实现呢?今天capucivar就将使用PHP来实现这个购物车的功能. 首先,做一个简单的首页,从数据库 ...
- [Angular 2] Create a simple search Pipe
This lesson shows you how to create a component and pass its properties as it updates into a Pipe to ...
- PHP安全编程:HTTP请求欺骗(转)
一个比欺骗表单更高级和复杂的攻击方式是HTTP请求欺骗.这给了攻击者完全的控制权与灵活性,它进一步证明了不能盲目信任用户提交的任何数据. 为了演示这是如何进行的,请看下面位于http://exampl ...
- Understanding Extension Class Loading--官方
http://docs.spring.io/spring-amqp/docs/1.3.6.RELEASE/reference/html/sample-apps.html#d4e1285 http:// ...
- checkbox 全选/取消
<html><script language=javascript>function selectAll(){var a = document.getElementsByTag ...
- C#解leetcode 152. Maximum Product Subarray
Find the contiguous subarray within an array (containing at least one number) which has the largest ...
- 基于bootstrap的轮播广告页,带图片和文字
<!DOCTYPE html> <html lang="zh-cn"> <head> <meta charset="utf-8& ...
- PHP magic_quotes_gpc的详细使用方法
工作中遇到的代码 if (ini_get('magic_quotes_gpc')) { function stripslashesRecursive(array $array){ foreach ($ ...