json映射

时间:2016-06-24 05:34:47

标签: c# json asp.net-mvc mailgun

我在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中,@eventkeyword已正确映射,因为它是@我假设使用前面的delivery-status个字符而且运作良好。但json中的delevery_status属性未与class DeliveryStatus中的deliveryStatus属性进行映射。我尝试将其创建为@deliver-status-。之前的onn不再映射,后者抛出编译时异常。无论如何都可以处理这些事情,比如声明中间有response json的属性?我无法更改null,因为它不会从我的结果生成。希望得到一些帮助。

更新

如下所述更改了类 this answer ,但没有帮助。再次public class Item { public string @event { get; set; } [JsonProperty(PropertyName = "delivery-status")] public DeliveryStatus deliveryStatus { get; set; } }

return rvo

1 个答案:

答案 0 :(得分:2)

我不确定问题到底是什么,但至少如果您使用此代码它会起作用。确保在项目中包含最新版本的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);
}