這篇文章主要為大家詳細(xì)介紹了.net實體類與json相互轉(zhuǎn)換的相關(guān)資料,感興趣的小伙伴們可以參考一下
.net實體類與json相互轉(zhuǎn)換時,注意要點(diǎn):
1.jsonhelp編寫時候添加的引用。System.Runtime.Serialization.Json;
2.實體類需聲明為public
jsonhelp代碼:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Runtime.Serialization.Json;
using System.IO;
namespace JsonTest
{
class JsonHelp
{
public JsonHelp()
{
//
// TODO: Add constructor logic here
//
}
/// <summary>
/// 把對象序列化 JSON 字符串
/// </summary>
/// <typeparam name="T">對象類型</typeparam>
/// <param name="obj">對象實體</param>
/// <returns>JSON字符串</returns>
public static string GetJson<T>(T obj)
{
//記住 添加引用 System.ServiceModel.Web
/**
* 如果不添加上面的引用,System.Runtime.Serialization.Json; Json是出不來的哦
* */
DataContractJsonSerializer json = new DataContractJsonSerializer(typeof(T));
using (MemoryStream ms = new MemoryStream())
{
json.WriteObject(ms, obj);
string szJson = Encoding.UTF8.GetString(ms.ToArray());
return szJson;
}
}
/// <summary>
/// 把JSON字符串還原為對象
/// </summary>
/// <typeparam name="T">對象類型</typeparam>
/// <param name="szJson">JSON字符串</param>
/// <returns>對象實體</returns>
public static T ParseFormJson<T>(string szJson)
{
T obj = Activator.CreateInstance<T>();
using (MemoryStream ms = new MemoryStream (Encoding.UTF8.GetBytes(szJson)))
{
DataContractJsonSerializer dcj = new DataContractJsonSerializer(typeof(T));
return (T)dcj.ReadObject(ms);
}
}
}
}
實體類代碼:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace JsonTest
{
public class testData
{
public testData()
{
}
public int Id { get; set; }
public string Name { get; set; }
public string Sex { get; set; }
}
}
控制臺應(yīng)用程序測試代碼:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace JsonTest
{
class Program
{
static void Main(string[] args)
{
//實體類轉(zhuǎn)json
testData t1 = new testData();
t1.Id = 1;
t1.Name = "001姓名";
t1.Sex = "男";
testData t2 = new testData();
t2.Id = 2;
t2.Name = "002姓名";
t2.Sex = "男";
testData t3 = new testData();
t3.Id = 3;
t3.Name = "003姓名";
t3.Sex = "男";
List<testData> tlist = new List<testData>();
tlist.Add(t1);
tlist.Add(t2);
tlist.Add(t3);
Console.WriteLine(JsonHelp.GetJson<List<testData>>(tlist));
// Console.ReadKey();
//json轉(zhuǎn)實體類
List<testData> tl = JsonHelp.ParseFormJson <List<testData>>(JsonHelp.GetJson<List<testData>>(tlist));
Console.WriteLine(tl.Count);
Console.WriteLine(tl[0].Name);
Console.ReadKey();
}
}
}
以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助