The conversion is completed using the javascriptserializer class in the Microsoft. NET class library. The data model used by the serial number defines public class study {
Public string name {Get; set ;}
Public int age {Get; set ;}
}
There are several methods to convert the background model to a JSON string:
1. serialize data directly into a JSON string
Study study = new study () {name = "hello", age = 22 };
Javascriptserializer serialize = new javascriptserializer ();
String result = serialize. serialize (study );
Result: {"name": "hello", "Age": 22}
2. serialization of Custom Data Objects using anonymous objects
Study study = new study () {name = "hello", age = 22 };
Javascriptserializer serialize = new javascriptserializer ();
String result = serialize. serialize (New {n = study. Name, A = study. Age });
Result: {"N": "hello", "A": 22}
3. inherit the javascriptconverter class to serialize Custom Data Objects.
Public class studyjsonconverter: javascriptconvertercodecode
{
Public override object deserialize (idictionary <string, Object> dictionary, type, javascriptserializer serializer)
{
If (Dictionary = NULL)
Return NULL;
If (type = typeof (Study ))
{
Study Result = new study ();
Result. Name = dictionary ["N"] as string;
Result. Age = convert. toint32 (Dictionary ["A"]);
Return result;
}
Return NULL;
}
Public override idictionary <string, Object> serialize (Object OBJ, javascriptserializer serializer)
{
Study study = OBJ as study;
Dictionary <string, Object> result = new dictionary <string, Object> ();
If (study! = NULL)
{
Result. Add ("N", study. Name );
Result. Add ("A", study. Age );
}
Return result;
}
Public override ienumerable <type> supportedtypes
{
Get {return New readonlycollection <type> (new list <type> () {typeof (Study )});}
}
}
Serialized object
Study study = new study () {name = "hello", age = 22 };
Javascriptserializer serialize = new javascriptserializer ();
Serialize. registerconverters (new list <javascriptconverter> () {New studyjsonconverter ()});
String result = serialize. serialize (study );
Result: {"N": "hello", "A": 22}
Comparison of several results
The first serialization method is the simplest, but the most problematic. When the latter data model changes, it will affect the front-end Javascript script, and the front-end and back-end connections are too close. The data model cannot be compressed.
The second and third types can compress the attributes of the data model, and the background model changes without affecting the Javascript script at the front end. Use different methods as needed.