我正在尝试将字符串解析为 JSON,如果我将其解析为
JObject
,它会起作用,但是如果我尝试解析为我自己的自定义类型,则当它尝试解析 Properties
时,我会收到错误
财产
错误:Newtonsoft.Json.JsonReaderException:'意外的字符 解析值时遇到:{.路径“属性”,第 1 行, 位置 212。'
var str2 = "{\"Timestamp\":\"2024-02-15T12:55:03.9797576+02:00\",\"Level\":\"Information\",\"MessageTemplate\":\"User profile is available. Using '{FullName}' as key repository and Windows DPAPI to encrypt keys at rest.\",\"Properties\":{\"FullName\":\"C:\\\\Users\\\\Buga\\\\AppData\\\\Local\\\\ASP.NET\\\\DataProtection-Keys\",\"EventId\":{\"Id\":63,\"Name\":\"UsingProfileAsKeyRepositoryWithDPAPI\"},\"SourceContext\":\"Microsoft.AspNetCore.DataProtection.KeyManagement.XmlKeyManager\"}}";
var obj = JsonConvert.DeserializeObject<JObject>(str2); // this works
var obj2 = JsonConvert.DeserializeObject<LogItem>(str2); // error here
public class LogItem
{
public DateTimeOffset Timestamp { get; set; }
public string Level { get; set; }
public string MessageTemplate { get; set; }
public string Properties { get; set; }
public string SourceContext { get; set; }
}
你有
string Properties
,所以它期待类似:
"Properties": "foo"
但是 JSON 有一个对象:
"Properties":{"FullName": ... }
所以,其中之一:
Properties
类型更改为合适的对象模型必须与数据匹配。
类似:
public class LogItem
{
public DateTimeOffset Timestamp { get; set; }
public string Level { get; set; }
public string MessageTemplate { get; set; }
public LogItemProperties Properties { get; set; }
}
public class LogItemProperties
{
public LogEventId EventId { get; set; }
public string FullName { get; set; }
public string SourceContext { get; set; }
}
public class LogEventId
{
public long Id { get; set; }
public string Name { get; set; }
}