1、安装引用Newtonsoft.Json(Json.NET)
1)使用Nuget安装
解决方案资源管理器 =》项目名字上右键 =》点击“管理Nuget程序包” =》搜索“Newtonsoft.Json” =》点击安装
2)直接下载指定版本
下载地址:https://github.com/JamesNK/Newtonsoft.Json/releases
2、Newtonsoft.Json(Json.NET)使用代码
相关文档:https://www.newtonsoft.com/json/help/html/SerializeObject.htm
public class Account { public string Email { get; set; } public bool Active { get; set; } public DateTime CreatedDate { get; set; } public IList<string> Roles { get; set; } }
1)对象转成Json字符
Account account = new Account { Email = "james@example.com", Active = true, CreatedDate = new DateTime(2013, 1, 20, 0, 0, 0, DateTimeKind.Utc), Roles = new List<string> { "User", "Admin" } }; string json = JsonConvert.SerializeObject(account, Formatting.Indented); // { // "Email": "james@example.com", // "Active": true, // "CreatedDate": "2013-01-20T00:00:00Z", // "Roles": [ // "User", // "Admin" // ] // } Console.WriteLine(json);
2)Json字符串转成对象
string json = @"{ 'Email': 'james@example.com', 'Active': true, 'CreatedDate': '2013-01-20T00:00:00Z', 'Roles': [ 'User', 'Admin' ] }"; Account account = JsonConvert.DeserializeObject<Account>(json); Console.WriteLine(account.Email); // james@example.com
3、反序列化成有Guid类型字段的对象解决方法
示例字符串
[{
"CustID": "f3b6.....0768bec",
"Title": "Timesheet",
"CalendarID": "AAMkADE5ZDViNmIyLWU3N2.....pVolcdmAABY3IuJAAA=",
"PartitionKey": "Project",
"RowKey": "94a6.....29a4f34",
"Timestamp": "2018-09-02T11:24:57.1838388+03:00",
"ETag": "W/\"datetime'2018-09-02T08%3A24%3A57.1838388Z'\""
}, {
"CustID": "5479b.....176643c",
"Title": "Galaxy",
"CalendarID": "AAMkADE5Z.......boA_pVolcdmAABZ8biCAAA=",
"PartitionKey": "Project",
"RowKey": "f5cc....86a4b",
"Timestamp": "2018-09-03T13:02:27.642082+03:00",
"ETag": "W/\"datetime'2018-09-03T10%3A02%3A27.642082Z'\""
}]
示例Project类
public class Project : TableEntity
{
public Project() { }
public Project(string rKey, string pKey = "Project")
{
this.PartitionKey = pKey;
this.RowKey = rKey;
}
public Guid CustID { get; set; }
public string Title { get; set; }
public string CalendarID { get; set; }
}
1)使用JsonConverter把反序列化中string转换为Guid类型
public class GuidJsonConverter : JsonConverter<Guid>
{
public override void WriteJson(JsonWriter writer, Guid value, JsonSerializer serializer)
{
writer.WriteValue(value.ToString());
}
public override Guid ReadJson(JsonReader reader, Type objectType, Guid existingValue, bool hasExistingValue, JsonSerializer serializer)
{
string s = (string)reader.Value;
return new Guid(s);
}
}
2)JsonConverter使用方法
对应字段上添加JsonConverter标签
[JsonConverter(typeof(GuidJsonConverter))]
public Guid CustID { get; set; }