C#實(shí)現(xiàn)簡單的JSON序列化功能代碼實(shí)例
好久沒有做web了,JSON目前比較流行,閑得沒事,所以動手試試將對象序列化為JSON字符(盡管DotNet Framework已經(jīng)有現(xiàn)成的庫,也有比較好的第三方開源庫),而且只是實(shí)現(xiàn)了處理簡單的類型,并且DateTime處理的也不專業(yè),有興趣的筒子可以擴(kuò)展,代碼比較簡單,反序列化木有實(shí)現(xiàn):( ,直接貼代碼吧,都有注釋了,所以廢話不多說 :)
測試類/// <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);
}
接口實(shí)現(xiàn),還有待完善..
/// <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]}
- C# Newtonsoft.Json 解析多嵌套json 進(jìn)行反序列化的實(shí)例
- C#使用Json.Net進(jìn)行序列化和反序列化及定制化
- C#實(shí)體對象序列化成Json并讓字段的首字母小寫的兩種解決方法
- C#中Json反序列化的實(shí)現(xiàn)方法
- C#中 Json 序列化去掉null值的方法
- C#實(shí)現(xiàn)JSON字符串序列化與反序列化的方法
- C#中實(shí)現(xiàn)Json序列化與反序列化的幾種方式
- C#實(shí)現(xiàn)的json序列化和反序列化代碼實(shí)例
- C#實(shí)現(xiàn)json的序列化和反序列化實(shí)例代碼
- c# 使用Json.NET實(shí)現(xiàn)json序列化
相關(guān)文章
C#基于Socket的TCP通信實(shí)現(xiàn)聊天室案例
這篇文章主要為大家詳細(xì)介紹了C#基于Socket的TCP通信實(shí)現(xiàn)聊天室案例,文中示例代碼介紹的非常詳細(xì),具有一定的參考價值,感興趣的小伙伴們可以參考一下2022-02-02Unity游戲開發(fā)實(shí)現(xiàn)背包系統(tǒng)的示例詳解
這篇文章主要為大家介紹了Unity游戲開發(fā)實(shí)現(xiàn)背包系統(tǒng)的示例詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2022-08-08C#/VB.NET實(shí)現(xiàn)在Word文檔中添加頁眉和頁腳
頁眉位于文檔中每個頁面的頂部區(qū)域,常用于顯示文檔的附加信息;頁腳位于文檔中每個頁面的底部的區(qū)域,常用于顯示文檔的附加信息。今天這篇文章就將為大家展示如何以編程的方式在在?Word?文檔中添加頁眉和頁腳2023-03-03C#實(shí)現(xiàn)關(guān)閉其他程序窗口或進(jìn)程代碼分享
這篇文章主要介紹了C#實(shí)現(xiàn)關(guān)閉其他程序窗口或進(jìn)程代碼分享,本文給出了兩種方法,并分別給出示例代碼,需要的朋友可以參考下2015-06-06解析C#設(shè)計(jì)模式編程中適配器模式的實(shí)現(xiàn)
這篇文章主要介紹了C#設(shè)計(jì)模式編程中適配器模式的實(shí)現(xiàn),分別舉了類的對象適配器與對象的適配器模式的例子,需要的朋友可以參考下2016-02-02Unity接入高德開放API實(shí)現(xiàn)IP定位
這篇文章主要為大家介紹了Unity如何接入高德開放API實(shí)現(xiàn)IP定位功能,文中的示例代碼講解詳細(xì),對我們學(xué)習(xí)或工作有一定參考價值,需要的可以參考一下2022-04-04