json 映射的 class 属性 声明无效

Invalid class property declaration for json mapping

我从 mailgun API 收到了以下 json

{
  "items": [{
    "delivery-status": {
      "message": null,
      "code": 605,
      "description": "Not delivering to previously bounced address",
      "session-seconds": 0
    },
    "event": "failed",
    "log-level": "error",
    "recipient": "test@test.com"
  },
  {
      //some other properties of above types
  }]
}

现在我试图为上面的 json 创建一个 class 结构来自动映射 deserializing 之后的属性。

public class test
{
    public List<Item> items { get; set; }
}
public class Item
{
    public string recipient { get; set; }
    public string @event { get; set; }
    public DeliveryStatus delivery_status { get; set; }
}

public class DeliveryStatus
{
    public string description { get; set; }
}

这就是我 deserialize 并尝试映射属性的方式。

var resp = client.Execute(request);
var json = new JavaScriptSerializer();
var content = json.Deserialize<Dictionary<string, object>>(resp.Content);
test testContent = (test)json.Deserialize(resp.Content, typeof(test));
var eventType = testContent.items[0].@event;
var desc = testContent.items[0].delivery_status.description; //stays null

现在在上面 class Itemrecipient@event 被正确映射并且因为它是 keyword 我应该使用前面的@ 个字符,效果很好。但是 json 中的 delivery-status 属性 不会映射到 class DeliveryStatus 中的 delevery_status 属性。我尝试将其创建为 deliveryStatus@deliver-status。较早的不会再次映射,而较晚的会抛出编译时异常。无论如何可以处理这些事情,比如在中间声明 属性 和 - 吗?我无法更改 response json,因为它不是从我这边生成的。希望得到一些帮助。

更新

将 class 更改为如下参考 this answer,但没有帮助。又是null

public class Item
{
    public string @event { get; set; }

    [JsonProperty(PropertyName = "delivery-status")]
    public DeliveryStatus deliveryStatus { get; set; }
}

我不确定你的问题是什么,但至少如果你使用这段代码它是有效的。确保在您的项目中包含 Newtonsoft.Json 的最新版本,您应该没问题。

public class DeliveryStatus
{
    public object message { get; set; }
    public int code { get; set; }
    public string description { get; set; }
    [JsonProperty("session-seconds")]
    public int session_seconds { get; set; }
}

public class Item
{
    [JsonProperty("delivery-status")]
    public DeliveryStatus delivery_status { get; set; }
    public string @event { get; set; }
    [JsonProperty("log-level")]
    public string log_level { get; set; }
    public string recipient { get; set; }
}

public class RootObject
{
    public List<Item> items { get; set; }
}

public static void Main(string[] args)
{
        string json = @"{
  ""items"": [{
    ""delivery-status"": {
                ""message"": null,
      ""code"": 605,
      ""description"": ""Not delivering to previously bounced address"",
      ""session-seconds"": 0
    },
    ""event"": ""failed"",
    ""log-level"": ""error"",
    ""recipient"": ""test@test.com""
  }]
}";

    RootObject r = JsonConvert.DeserializeObject<RootObject>(json);
}