- Similar to the previous section
- We can parse a JSON string into an array
- Simply replace the original class name with
List<ClassName>
Example
string jsonString = @"""{""webinfos"":[{""webname"":""FoxDevelop"",""website"":""foxdevelop.com"",""age"":4,
""students"":[{""name"":""Oliver""},{""name"":""Noah""}]},{""webname"":""FoxDevelop1"",""website"":""foxdevelop.com1"",
""age"":6,""students"":[{""name"":""Liam""},{""name"":""Ethan""}]}]}""";
StringReader sr = new StringReader(jsonString);
JsonReader jr = new JsonReader(sr);
List<WebInfo> infoList = new JsonSerializer().Deserialize(jr, typeof(List<WebInfo>)) as List<WebInfo>;Code language: PHP (php)
Notes
- Keep code structure, variable names, escaped double‑quotes and line breaks unchanged, only replace target text
- Do not modify subsequent deserialization logic
① Serialize List to JSON array string
// Construct List collection
List<WebInfo> webList = new List<WebInfo>()
{
new WebInfo()
{
age = 4,
webname = "FoxDevelop",
website = "foxdevelop.com",
students = new Person[] { new Person{name="Oliver"}, new Person{name="Noah"} }
},
new WebInfo()
{
age = 4,
webname = "FoxDevelop1",
website = "foxdevelop.com",
students = new Person[] { new Person{name="Liam"}, new Person{name="Ethan"} }
},
new WebInfo()
{
age = 4,
webname = "FoxDevelop2",
website = "foxdevelop.com",
students = new Person[] { new Person{name="Mason"}, new Person{name="Logan"} }
}
};
// Serialize: List object → JSON‑array string
StringWriter sw = new StringWriter();
JsonWriter writer = new JsonWriter(sw);
new JsonSerializer().Serialize(writer, webList);
string jsonArrStr = sw.GetStringBuilder().ToString();Code language: PHP (php)
② Deserialize JSON‑array string to List
string jsonString = @"[{"webname":"FoxDevelop","website":"foxdevelop.com","age":4,
"students":[{"name":"Oliver"},{"name":"Noah"}]},{"webname":"FoxDevelop1","website":"foxdevelop.com",
"age":4,"students":[{"name":"Liam"},{"name":"Ethan"}]},{"webname":"FoxDevelop2","website":"foxdevelop.com",
"age":4,"students":[{"name":"Mason"},{"name":"Logan"}]}]";
StringReader sr = new StringReader(jsonString);
JsonReader jr = new JsonTextReader(sr);
List<WebInfo> dataList = new JsonSerializer().Deserialize(jr, typeof(List<WebInfo>)) as List<WebInfo>;Code language: PHP (php)
Array serialization and deserialization
Previous: Serialization and deserialization