我在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
已正确映射,因为它是@
我假设使用前面的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
答案 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);
}