Newtonsoft.Json.JsonReaderException:'解析值时遇到意外字符:{。路径

问题描述 投票:0回答:1

我正在尝试将字符串解析为 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; }
 }
json .net serialization json.net
1个回答
1
投票

你有

string Properties
,所以它期待类似:

"Properties": "foo"

但是 JSON 有一个对象:

"Properties":{"FullName": ... }

所以,其中之一:

  • Properties
    类型更改为合适的对象
  • 使用具有 string 属性的 JSON

模型必须与数据匹配。

类似:

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; }
}
© www.soinside.com 2019 - 2024. All rights reserved.