无效的json映射类属性声明

本文关键字:属性 声明 映射 json 无效 | 更新日期: 2023-09-27 17:49:18

我有以下json收到mailgun API

{
  "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创建一个类结构来自动映射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

现在在上面的类Item, recipient@event得到正确的映射,因为它是keyword,我应该使用前面的@字符,它工作得很好。但是json中的delivery-status属性没有映射到class DeliveryStatus中的delevery_status属性。我试着创建它作为deliveryStatus@deliver-status。前一个不能再映射,后一个抛出编译时异常。无论如何,这些事情可以处理,像声明一个属性与-之间?我不能改变response json,因为它不是从我的端生成的。希望得到一些帮助。

参照 this answer 更改了下面的类,但没有帮助。又是null

public class Item
{
    public string @event { get; set; }
    [JsonProperty(PropertyName = "delivery-status")]
    public DeliveryStatus deliveryStatus { get; set; }
}

无效的json映射类属性声明

我不确定您的问题是什么,但至少如果您使用此代码,它可以工作。请确保包含最新版本的Newtonsoft。

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);
}