C#实现简单的JSON序列化功能代码实例
好久没有做web了,json目前比较流行,闲得没事,所以动手试试将对象序列化为json字符(尽管dotnet framework已经有现成的库,也有比较好的第三方开源库),而且只是实现了处理简单的类型,并且datetime处理的也不专业,有兴趣的筒子可以扩展,代码比较简单,反序列化木有实现:( ,直接贴代码吧,都有注释了,所以废话不多说 :)
测试类/// <summary>
/// nested class of person.
/// </summary>
public class house
{
public string name
{
get;
set;
}
public double price
{
get;
set;
}
}
/// <summary>
/// person dummy class
/// </summary>
public class person
{
public string name
{
get;
set;
}
public int age
{
get;
set;
}
public string address
{
get;
set;
}
private int h = 12;
public bool ismarried
{
get;
set;
}
public string[] names
{
get;
set;
}
public int[] ages
{
get;
set;
}
public house myhouse
{
get;
set;
}
public datetime birthday
{
get;
set;
}
public list<string> friends
{
get;
set;
}
public list<int> lovenumbers
{
get;
set;
}
}
接口定义 /// <summary>
/// ijsonserializer interface.
/// </summary>
interface ijsonserializer
{
/// <summary>
/// serialize object to json string.
/// </summary>
/// <typeparam name="t">the type to be serialized.</typeparam>
/// <param name="obj">instance of the type t.</param>
/// <returns>json string.</returns>
string serialize(object obj);
/// <summary>
/// deserialize json string to object.
/// </summary>
/// <typeparam name="t">the type to be deserialized.</typeparam>
/// <param name="jsonstring">json string.</param>
/// <returns>instance of type t.</returns>
t deserialize<t>(string jsonstring);
}
接口实现,还有待完善..
/// <summary>
/// implement ijsonserializer, but deserialize had not been implemented.
/// </summary>
public class jsonserializer : ijsonserializer
{
/// <summary>
/// serialize object to json string.
/// </summary>
/// <typeparam name="t">the type to be serialized.</typeparam>
/// <param name="obj">instance of the type t.</param>
/// <returns>json string.</returns>
public string serialize(object obj)
{
if (obj == null)
{
return "{}";
}
// get the type of obj.
type t = obj.gettype();
// just deal with the public instance properties. others ignored.
bindingflags bf = bindingflags.instance | bindingflags.public;
propertyinfo[] pis = t.getproperties(bf);
stringbuilder json = new stringbuilder("{");
if (pis != null && pis.length > 0)
{
int i = 0;
int lastindex = pis.length - 1;
foreach (propertyinfo p in pis)
{
// simple string
if (p.propertytype.equals(typeof(string)))
{
json.appendformat("\"{0}\":\"{1}\"", p.name, p.getvalue(obj, null));
}
// number,boolean.
else if (p.propertytype.equals(typeof(int)) ||
p.propertytype.equals(typeof(bool)) ||
p.propertytype.equals(typeof(double)) ||
p.propertytype.equals(typeof(decimal))
)
{
json.appendformat("\"{0}\":{1}", p.name, p.getvalue(obj, null).tostring().tolower());
}
// array.
else if (isarraytype(p.propertytype))
{
// array case.
object o = p.getvalue(obj, null);
if (o == null)
{
json.appendformat("\"{0}\":{1}", p.name, "null");
}
else
{
json.appendformat("\"{0}\":{1}", p.name, getarrayvalue((array)p.getvalue(obj, null)));
}
}
// class type. custom class, list collections and so forth.
else if (iscustomclasstype(p.propertytype))
{
object v = p.getvalue(obj, null);
if (v is ilist)
{
ilist il = v as ilist;
string subjsstring = getilistvalue(il);
json.appendformat("\"{0}\":{1}", p.name, subjsstring);
}
else
{
// normal class type.
string subjsstring = serialize(p.getvalue(obj, null));
json.appendformat("\"{0}\":{1}", p.name, subjsstring);
}
}
// datetime
else if (p.propertytype.equals(typeof(datetime)))
{
datetime dt = (datetime)p.getvalue(obj, null);
if (dt == default(datetime))
{
json.appendformat("\"{0}\":\"\"", p.name);
}
else
{
json.appendformat("\"{0}\":\"{1}\"", p.name, ((datetime)p.getvalue(obj, null)).tostring("yyyy-mm-dd hh:mm:ss"));
}
}
else
{
// todo: extend.
}
if (i >= 0 && i != lastindex)
{
json.append(",");
}
++i;
}
}
json.append("}");
return json.tostring();
}
/// <summary>
/// deserialize json string to object.
/// </summary>
/// <typeparam name="t">the type to be deserialized.</typeparam>
/// <param name="jsonstring">json string.</param>
/// <returns>instance of type t.</returns>
public t deserialize<t>(string jsonstring)
{
throw new notimplementedexception("not implemented :(");
}
/// <summary>
/// get array json format string value.
/// </summary>
/// <param name="obj">array object</param>
/// <returns>js format array string.</returns>
string getarrayvalue(array obj)
{
if (obj != null)
{
if (obj.length == 0)
{
return "[]";
}
object firstelement = obj.getvalue(0);
type et = firstelement.gettype();
bool quotable = et == typeof(string);
stringbuilder sb = new stringbuilder("[");
int index = 0;
int lastindex = obj.length - 1;
if (quotable)
{
foreach (var item in obj)
{
sb.appendformat("\"{0}\"", item.tostring());
if (index >= 0 && index != lastindex)
{
sb.append(",");
}
++index;
}
}
else
{
foreach (var item in obj)
{
sb.append(item.tostring());
if (index >= 0 && index != lastindex)
{
sb.append(",");
}
++index;
}
}
sb.append("]");
return sb.tostring();
}
return "null";
}
/// <summary>
/// get ilist json format string value.
/// </summary>
/// <param name="obj">ilist object</param>
/// <returns>js format ilist string.</returns>
string getilistvalue(ilist obj)
{
if (obj != null)
{
if (obj.count == 0)
{
return "[]";
}
object firstelement = obj[0];
type et = firstelement.gettype();
bool quotable = et == typeof(string);
stringbuilder sb = new stringbuilder("[");
int index = 0;
int lastindex = obj.count - 1;
if (quotable)
{
foreach (var item in obj)
{
sb.appendformat("\"{0}\"", item.tostring());
if (index >= 0 && index != lastindex)
{
sb.append(",");
}
++index;
}
}
else
{
foreach (var item in obj)
{
sb.append(item.tostring());
if (index >= 0 && index != lastindex)
{
sb.append(",");
}
++index;
}
}
sb.append("]");
return sb.tostring();
}
return "null";
}
/// <summary>
/// check whether t is array type.
/// </summary>
/// <param name="t"></param>
/// <returns></returns>
bool isarraytype(type t)
{
if (t != null)
{
return t.isarray;
}
return false;
}
/// <summary>
/// check whether t is custom class type.
/// </summary>
/// <param name="t"></param>
/// <returns></returns>
bool iscustomclasstype(type t)
{
if (t != null)
{
return t.isclass && t != typeof(string);
}
return false;
}
}
测试代码:
class program
{
static void main(string[] args)
{
person ps = new person()
{
name = "leon",
age = 25,
address = "china",
ismarried = false,
names = new string[] { "wgc", "leon", "giantfish" },
ages = new int[] { 1, 2, 3, 4 },
myhouse = new house()
{
name = "housename",
price = 100.01,
},
birthday = new datetime(1986, 12, 20, 12, 12, 10),
friends = new list<string>() { "friend1", "friend2" },
lovenumbers = new list<int>() { 1, 2, 3 }
};
ijsonserializer js = new jsonserializer();
string s = js.serialize(ps);
console.writeline(s);
console.readkey();
}
}
生成的 json字符串 :
{"name":"leon","age":25,"address":"china","ismarried":false,"names":["wgc","leon","giantfish"],"ages":[1,2,3,4],"myhouse":{"name":"housename","price":100.01},"birthday":"1986-12-20 12:12:10","friends":["friend1","friend2"],"lovenumbers":[1,2,3]}