.net 的 Newtonsoft JSON 忽略 jsonproperty 标签

时间:2023-04-25
本文介绍了.net 的 Newtonsoft JSON 忽略 jsonproperty 标签的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着跟版网的小编来一起学习吧!

问题描述

出于一些真正令人恼火的原因,JsonProperty 标签无法与 Newtonsoft 的 Json for .net 工具一起使用.在我的课堂上,我有这些:

For some really irritating reason, the JsonProperty tags are not working with Newtonsoft's Json for .net tool. In my class I have these:

    [JsonProperty(PropertyName = "id")]
    public string ID { get; set; }
    [JsonProperty(PropertyName = "title")]
    public string Title { get; set; }
    [JsonProperty(PropertyName = "url")]
    public string Url { get; set; }
    [JsonProperty(PropertyName = "class")]
    public string EventClass { get; set; }
    [JsonProperty(PropertyName = "start")]
    public string Start { get; set; }
    [JsonProperty(PropertyName = "end")]
    public string End { get; set; }

但是我收到了这个

{"success":true,
 "result": [{
    "ID":"0",
    "Title":"Eid ul-Fitr",
    "Url":"<blah>",
    "EventClass":"event-info",
    "Start":"1406520000000",
    "End":"1406606400000"},
  etc.

如您所见,它忽略了我设置属性名称.我也尝试过使用 [System.Runtime.Serialization.DataMember(Name="id")] 但没有奏效.

As you can see it is ignoring me setting the property name. I have tried using [System.Runtime.Serialization.DataMember(Name="id")] as well and that has not worked.

这才是真正让我陷入困境的原因.它昨天奏效了.我把它回滚到昨晚我提交时的位置,但它仍然无法工作.

Here is what is really driving me up the wall. It worked yesterday. I rolled it back to where it was last night when I committed and it still won't work.

有什么想法吗?

推荐答案

您确定您实际上是在使用 Json.Net 进行序列化吗?Json(MyClass) 是一种 ASP.NET MVC 方法.MVC 使用 JavaScriptSerializer 类,该类不支持 [JsonProperty] 属性.要使用这些属性,您需要使用 Json.Net 方法 JsonConvert.SerializeObject(MyClass) 进行序列化.如果您想从 MVC 控制器中返回该 JSON,则需要调用 Content(jsonString, "application/json") 而不是 Json().

Are you sure you're actually serializing using Json.Net? Json(MyClass) is an ASP.NET MVC method. MVC uses the JavaScriptSerializer class, which does not support [JsonProperty] attributes. To use the attributes, you would need to serialize using the Json.Net method JsonConvert.SerializeObject(MyClass). If you want to return that JSON from within an MVC controller then you would need call Content(jsonString, "application/json") instead of Json().

这篇关于.net 的 Newtonsoft JSON 忽略 jsonproperty 标签的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

上一篇:Json.Net 反序列化内存不足问题 下一篇:使用 JSON.NET 序列化/反序列化动态属性名称

相关文章