您的位置:首页 > Web前端 > JavaScript

将List对象列表转换成JSON格式的类

2008-11-26 20:05 495 查看
source:/article/5638872.html
将List对象列表转换成JSON格式的类
JSON(JavaScript Object Notation) 是一种轻量级的数据交换格式。易于人阅读和编写。同时也易于机器解析和生成。它基于JavaScript Programming Language, Standard ECMA-262 3rd Edition - December 1999的一个子集。 JSON采用完全独立于语言的文本格式,但是也使用了类似于C语言家族的习惯(包括C, C++, C#, Java, JavaScript, Perl, Python等)。这些特性使JSON成为理想的数据交换语言。引用于[http://www.json.org/json-zh.html]

一般应用中,我习惯性地把结果集以更通用的IList<object>对象列表方式保存(可能会对性能有些影响)来保证类间交互时的通用性,降低函数功能对具体类的耦合。但AJAX调用时,还需要把对象列表转换成JSON数据交给前端显示。有麻烦。

研究了一下JSON的对象定义和集合定义





感觉利用反射来生成JSON还比较方便。代码如下:




Code
1 //
2 // ObjectListToJSON
3 // Copyright (c) 2008 pcode. All rights reserved.
4 //
5 // Author(s):
6 //
7 // pcode,jy@cjlu.edu.cn
8 // 此类用于将List<object>转换为json数据格式
9 // 目前仅能处理一个object的基础数据类型而且对[ { }] /等对json有伤害影响特殊符号没有特殊处理
10 // 希望有兄弟继续完善
11
12 using System.Reflection;
13 using System.Collections.Generic;
14
15 public class ObjectListToJSON
16 {
17 #region 反射一个对象所有属性和属性值和将一个对象的反射结果封装成jsons格式
18 /**
19 * 对象的全部属性和属性值。用于填写json的{}内数据
20 * 生成后的格式类似
21 * "属性1":"属性值"
22 * 将这些属性名和属性值写入字符串列表返回
23 * */
24 private List<string> GetObjectProperty(object o)
25 {
26 List<string> propertyslist = new List<string>();
27 PropertyInfo[] propertys = o.GetType().GetProperties();
28 foreach (PropertyInfo p in propertys)
29 {
30 propertyslist.Add("/"" + p.Name.ToString() + "/":/"" + p.GetValue(o, null) + "/"");
31 }
32 return propertyslist;
33 }
34 /**
35 * 将一个对象的所有属性和属性值按json的格式要求输入为一个封装后的结果。
36 *
37 * 返回值类似{"属性1":"属性1值","属性2":"属性2值","属性3":"属性3值"}
38 *
39 * */
40 private string OneObjectToJSON(object o)
41 {
42 string result = "{";
43 List<string> ls_propertys = new List<string>();
44 ls_propertys = GetObjectProperty(o);
45 foreach (string str_property in ls_propertys)
46 {
47 if (result.Equals("{"))
48 {
49 result = result + str_property;
50 }
51 else
52 {
53 result = result + "," + str_property + "";
54 }
55 }
56 return result + "}";
57 }
58 #endregion
59 /**
60 * 把对象列表转换成json串
61 * */
62 public string toJSON(List<object> objlist)
63 {//覆写,给懒人一个不写classname的机会
64 return toJSON(objlist, string.Empty);
65 }
66 public string toJSON(List<object> objlist, string classname)
67 {
68 string result = "{";
69 if (classname.Equals(string.Empty))//如果没有给定类的名称,那么自做聪明地安一个
70 {
71 object o = objlist[0]
72 classname = o.GetType().ToString();
73 }
74 result += "/"" + classname + "/":[";
75 bool firstline = true;//处理第一行前面不加","号
76 foreach (object oo in objlist)
77 {
78 if (!firstline)
79 {
80 result = result + "," + OneObjectToJSON(oo);
81 }
82 else
83 {
84 result = result + OneObjectToJSON(oo) + "";
85 firstline = false;
86 }
87 }
88 return result + "]}";
89 }
90
91 }
92
OK,我们建立一个测试来验证一下它是否生效。

先建立一个对象定义person.cs




Code
namespace Model
{
public class Person
{
public string ID { get; set; }
public string Name { get; set; }
public string Sex { get; set; }
}
}

然后建立测试类

我用了一种非常原始的方法生成了对象列表,其实可以从数据库查询,怕把事情搞得太复杂。呵呵。




Code
using NUnit.Framework;
using System.Collections.Generic;
namespace JSon
{
[TestFixture]
public class TestObjectToJSON
{
[Test]
public void dotest() {
Model.Person p1 = new Model.Person();
p1.ID = "1";
p1.Name = "p1";
p1.Sex = "s1";
Model.Person p2 = new Model.Person();
p2.ID = "2";
p2.Name = "p2";
p2.Sex = "s2";

Model.Person p3 = new Model.Person();
p3.ID = "3";
p3.Name = "p3";
p3.Sex = "s3";
List<object> lp = new List<object>();
lp.Add(p1);
lp.Add(p2);
lp.Add(p3);

ObjectListToJSON t = new ObjectListToJSON();
string json = t.toJSON(lp, "persons");
System.Console.Write(json);
}
}
}

跑一下Nuint,我们想要的json串已经生成了。



Tag标签: JSON,对象列表,List,转换
posted on 2008-11-26 16:54 源姜 阅读(233) 评论(3) 编辑 收藏 网摘



发表评论

回复 引用 查看 2008-11-26 17:21 | 上不了岸的鱼{ttzhang}
沙发,嘿嘿...

回复 引用 查看 2008-11-26 18:29 | 圣盗
可以参考 FrameWork3.5中的 System.Web.Script.Serialization命名空间,其中提供了JSON脚本序列化和反序列化的一些类

回复 引用 查看 2008-11-26 20:02 | 源姜
--引用--------------------------------------------------
圣盗: 可以参考 FrameWork3.5中的 System.Web.Script.Serialization命名空间,其中提供了JSON脚本序列化和反序列化的一些类
--------------------------------------------------------
现在因为Nhibernate还没支持3.5,我还坚守在2.0的阵地上。

function GetQuote(id)
{
//www.cnblogs.com.ICommentService.GetCommentText(id,SetQuote);
BlogServer.WebService.AjaxWS.GetComment(id,SetQuote);
}

function SetQuote(result)
{
document.getElementById('AjaxHolder_PostComment_tbComment').value+= ("--引用--------------------------------------------------/n"+result+"/n--------------------------------------------------------/n");
document.getElementById('AjaxHolder_PostComment_tbComment').focus();
}

function Favorite(entryID,title,url,element)
{
document.getElementById(element.id).innerHTML = "正在收藏...";
BlogServer.WebService.AjaxWS.AddToFavorites(entryID,title,url,OnFavoriteSuccess);
document.getElementById(element.id).removeAttribute("href");
document.getElementById(element.id).removeAttribute("onclick");
}

function OnFavoriteSuccess(result)
{
if(result == "请先登录")
{
window.location.href = "../../../../../login.aspx?ReturnUrl=" + window.location.href;
}
else
{
var returnstr = result.split(",");
var id = "lnkFavorite"+returnstr[0];
document.getElementById(id).innerHTML = "" + returnstr[1] + "";
}
}

function DelComment(id,element)
{
if(confirm("确认要删除该评论吗?"))
{
document.getElementById(element.id).innerHTML = "正在删除...";
BlogServer.WebService.AjaxWS.DelComment(id,del_comment_callback);
}
return false;
}

function del_comment_callback(response)
{
__doPostBack('AjaxHolder$PostComment$refreshList','');
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: