Newtonsoft.Json
来自软件开发
安装
Install-Package Newtonsoft.Json
Serialize JSON
示例代码:
Product product = new Product(); product.Name = "Apple"; product.Expiry = new DateTime(2008, 12, 28); product.Sizes = new string[] { "Small" }; string json = JsonConvert.SerializeObject(product); // { // "Name": "Apple", // "Expiry": "2008-12-28T00:00:00", // "Sizes": [ // "Small" // ] // }
Deserialize JSON
string json = @"{ 'Name': 'Bad Boys', 'ReleaseDate': '1995-4-7T00:00:00', 'Genres': [ 'Action', 'Comedy' ] }"; Movie m = JsonConvert.DeserializeObject<Movie>(json); string name = m.Name; // Bad Boys
LINQ to JSON
JArray array = new JArray(); array.Add("Manual text"); array.Add(new DateTime(2000, 5, 23)); JObject o = new JObject(); o["MyArray"] = array; string json = o.ToString(); // { // "MyArray": [ // "Manual text", // "2000-05-23T00:00:00" // ] // }
数据类
序列化模式有两种:OptOut:除外模式、OptIn:包含模式。
A1 OptOut:除外模式
需要给类标记[JsonObject(MemberSerialization.OptOut)],给类成员标记[JsonIgnore]
A2 OptIn:包含模式
需要给类标记[JsonObject(MemberSerialization.OptIn)],给类成员标记[JsonProperty] ,由于和A1例子相似此处就不举例子了。
[JsonObject(MemberSerialization.OptIn)] public class Person { // "John Smith" [JsonProperty] public string Name { get; set; } // "2000-12-15T22:11:03" [JsonProperty] public DateTime BirthDate { get; set; } // new Date(976918263055) [JsonProperty] public DateTime LastModified { get; set; } // not serialized because mode is opt-in public string Department { get; set; } }
https://blog.csdn.net/weixin_45582785/article/details/105927460