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]}
相关文章
- 这篇文章主要介绍了gin 获取post请求的json body操作,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧...2021-03-15
- 新版 Mysql 中加入了对 JSON Document 的支持,可以创建 JSON 类型的字段,并有一套函数支持对JSON的查询、修改等操作,下面就实际体验一下...2016-08-23
- JSON(JavaScript Object Notation) 是一种轻量级的数据交换格式。JSON采用完全独立于语言的文本格式,这些特性使JSON成为理想的数据交换语言。易于人阅读和编写,同时也易于机器解析和生成...2021-11-05
C#使用Http Post方式传递Json数据字符串调用Web Service
这篇文章主要为大家详细介绍了C#使用Http Post方式传递Json数据字符串调用Web Service,具有一定的参考价值,感兴趣的小伙伴们可以参考一下...2020-06-25- 下面小编就为大家带来一篇js遍历json的key和value的实例。小编觉得挺不错的,现在就分享给大家,也给大家做个参考。一起跟随小编过来看看吧...2017-01-26
- 这篇文章主要介绍了详解.NET Core 3.0 里新的JSON API,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧...2021-09-22
ASP.NET Core根据环境变量支持多个 appsettings.json配置文件
这篇文章主要介绍了ASP.NET Core根据环境变量支持多个 appsettings.json配置文件,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧...2021-09-22基于Vue+Openlayer实现动态加载geojson的方法
本文通过实例代码给大家介绍基于Vue+Openlayer实现动态加载geojson的方法,代码简单易懂,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友参考下吧...2021-09-01- 下面就为大家带来一篇jquery对Json的各种遍历方法总结(必看篇)。小编觉得挺不错的,现在就分享给大家,也给大家做个参考。一起跟随小编过来看看吧...2016-10-02
解决HttpPost+json请求---服务器中文乱码及其他问题
这篇文章主要介绍了解决HttpPost+json请求---服务器中文乱码及其他问题,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧...2021-01-22- 本文给大家介绍如何替换json对象中的key,通过实例代码给大家介绍key的替换方法,代码也很简单,需要的朋友参考下吧...2021-06-02
JSON字符串转换JSONObject和JSONArray的方法
这篇文章主要介绍了JSON字符串转换JSONObject和JSONArray的方法的相关资料,需要的朋友可以参考下...2016-06-12- 这篇文章主要介绍了解决Golang json序列化字符串时多了\的情况,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧...2020-12-24
使用MSScriptControl 在 C# 中读取json数据的方法
下面小编就为大家带来一篇使用MSScriptControl 在 C# 中读取json数据的方法。小编觉得挺不错的,现在就分享给大家,也给大家做个参考。一起跟随小编过来看看吧...2020-06-25- 在js中用了JSON.parse方法在IE8,IE9,IE10兼容模式下提示JSON未定义,搜狗等IE内核的浏览器则是功能失效chrome谷歌浏览器表现一如既往的好用解决办法:判断当前浏览器是否支持JSON...2013-08-20
Springmvc ResponseBody响应json数据实现过程
这篇文章主要介绍了Springmvc ResponseBody响应json数据实现过程,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下...2020-10-26java HttpClient传输json格式的参数实例讲解
这篇文章主要介绍了java HttpClient传输json格式的参数实例讲解,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧...2021-01-22- 这篇文章主要介绍了微信小程序通过api接口将json数据展现到小程序示例,小编觉得挺不错的,现在分享给大家,也给大家做个参考。一起跟随小编过来看看吧...2017-01-23
- 这篇文章主要介绍了vs中 C#项目读取JSON配置文件的相关知识,本文通过实例代码给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友可以参考下...2020-06-25
- 这篇文章主要介绍了C#实现将类的内容写成JSON格式字符串的方法,涉及C#针对json格式数据转换的相关技巧,具有一定参考借鉴价值,需要的朋友可以参考下...2020-06-25