When. NET entity classes are converted to JSON, note the main points:
1.jsonhelp the reference added when writing. System.Runtime.Serialization.Json;
2. Entity classes need to be declared public
Jsonhelp Code:
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 ///<summary>///Serializes the object to the JSON string///</summary>///<typeparam name= "T" > Object type </typep aram>///<param name= "obj" > object entity </param>///<returns>json string </returns> public static str ing getjson<t> (T obj) {//Remember to add Reference System.ServiceModel.Web/** * If the above reference is not added, System.Runtime.Serializat Ion. Json;
JSON doesn't come out. * * * * * * * * * 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>///restores JSON strings to objects </summary>///<typeparam name= "T" > Object type </typeparam>///<param name= "Szjson" >json string < /param>///<returns> Object entity </returns> public static T parseformjson<t> (string szjson) {T obj
= Activator.createinstance<t> (); using (MemoryStream ms = new MemoryStream (Encoding.UTF8.GetBytes (Szjson)) {DataContractJsonSerializer DCJ = n
EW DataContractJsonSerializer (typeof (T)); Return (T) DCJ.
ReadObject (MS);
}
}
}
}
Entity Class Code:
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;}}}
Console Application test code:
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) {//entity class goto JSON TestData t1 =
New TestData (); T1.
Id = 1; T1.
Name = "001 name"; T1.
Sex = "male";
TestData t2 = new TestData (); T2.
Id = 2; T2.
Name = "002 Name"; T2.
Sex = "male";
testData t3 = new TestData (); T3.
Id = 3; T3.
Name = "003 Name"; T3.
Sex = "male";
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 to entity class list<testdata> TL = Jsonhelp.parseformjson <List<testData>> (jsonhelp.getjson<list&l
T;testdata>> (tlist)); Console.WriteLine (TL.
Count); Console.WriteLine (Tl[0].
Name);
Console.readkey (); }
}
}
The above is the entire content of this article, I hope to help you learn, but also hope that we support the cloud habitat community.