.net实体类与json相互转换
.net实体类与json相互转换时,注意要点:
1.jsonhelp编写时候添加的引用。System.Runtime.Serialization.Json;
2.实体类需声明为public
jsonhelp代码:
usingSystem; usingSystem.Collections.Generic; usingSystem.Linq; usingSystem.Text; usingSystem.Threading.Tasks; usingSystem.Runtime.Serialization.Json; usingSystem.IO; namespaceJsonTest { classJsonHelp { publicJsonHelp() { // //TODO:Addconstructorlogichere // } ///<summary> ///把对象序列化JSON字符串 ///</summary> ///<typeparamname="T">对象类型</typeparam> ///<paramname="obj">对象实体</param> ///<returns>JSON字符串</returns> publicstaticstringGetJson<T>(Tobj) { //记住添加引用System.ServiceModel.Web /** *如果不添加上面的引用,System.Runtime.Serialization.Json;Json是出不来的哦 **/ DataContractJsonSerializerjson=newDataContractJsonSerializer(typeof(T)); using(MemoryStreamms=newMemoryStream()) { json.WriteObject(ms,obj); stringszJson=Encoding.UTF8.GetString(ms.ToArray()); returnszJson; } } ///<summary> ///把JSON字符串还原为对象 ///</summary> ///<typeparamname="T">对象类型</typeparam> ///<paramname="szJson">JSON字符串</param> ///<returns>对象实体</returns> publicstaticTParseFormJson<T>(stringszJson) { Tobj=Activator.CreateInstance<T>(); using(MemoryStreamms=newMemoryStream(Encoding.UTF8.GetBytes(szJson))) { DataContractJsonSerializerdcj=newDataContractJsonSerializer(typeof(T)); return(T)dcj.ReadObject(ms); } } } }
实体类代码:
usingSystem; usingSystem.Collections.Generic; usingSystem.Linq; usingSystem.Text; usingSystem.Threading.Tasks; namespaceJsonTest { publicclasstestData { publictestData() { } publicintId{get;set;} publicstringName{get;set;} publicstringSex{get;set;} } }
控制台应用程序测试代码:
usingSystem; usingSystem.Collections.Generic; usingSystem.Linq; usingSystem.Text; usingSystem.Threading.Tasks; namespaceJsonTest { classProgram { staticvoidMain(string[]args) { //实体类转json testDatat1=newtestData(); t1.Id=1; t1.Name="001姓名"; t1.Sex="男"; testDatat2=newtestData(); t2.Id=2; t2.Name="002姓名"; t2.Sex="男"; testDatat3=newtestData(); t3.Id=3; t3.Name="003姓名"; t3.Sex="男"; List<testData>tlist=newList<testData>(); tlist.Add(t1); tlist.Add(t2); tlist.Add(t3); Console.WriteLine(JsonHelp.GetJson<List<testData>>(tlist)); //Console.ReadKey(); //json转实体类 List<testData>tl=JsonHelp.ParseFormJson<List<testData>>(JsonHelp.GetJson<List<testData>>(tlist)); Console.WriteLine(tl.Count); Console.WriteLine(tl[0].Name); Console.ReadKey(); } } }
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持毛票票。