【问题标题】:Is there a way to change Property Name in JSON data有没有办法更改 JSON 数据中的属性名称
【发布时间】:2016-12-18 04:26:55
【问题描述】:

有什么方法可以更改我通过 Web API 从 JSON 响应返回的列/属性名称

示例 JSON 响应:

[
 {
  "ActualPropName1": "Value1", //change ActualPropName1 to something else
  "ActualPropName2": "Value2"
 }
]

我尝试在模型上使用数据注释,但是,它似乎没有达到我想要的效果

[DisplayName("Generic Name")]
public string ActualPropName1{ get; set; }

【问题讨论】:

  • 您可以将Json.NET[JsonProperty(PropertyName = "FooBar")] 应用于您的属性
  • 应用上述建议后我没有收到任何错误,但 JSON 仍然返回实际的属性名称。
  • 这是用于序列化或反序列化的时候吗?如果序列化,那么为什么不直接返回一个匿名对象,或者在序列化之前将其映射到另一个具有替代名称的视图模型

标签: asp.net json asp.net-mvc asp.net-web-api


【解决方案1】:

您可以简单地拥有一个具有所需名称的新属性,该属性只需从其他属性返回数据。然后隐藏/忽略另一个:

[JsonIgnore]
public string ActualPropName1 { get; set; }

public string GenericName
{
    get
    {
        return ActualPropName1;
    }
}

尽管从您的示例来看,这不适用于像“通用名称”这样的属性名称。

【讨论】:

    【解决方案2】:

    你可以使用 JSON.NET 的 JsonProperty

    [JsonProperty(PropertyName="Your_Name")]
    public string ActualPropName1{ get; set; }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-11-29
      • 2013-02-19
      • 1970-01-01
      • 1970-01-01
      • 2019-09-24
      • 1970-01-01
      • 2010-10-08
      • 1970-01-01
      相关资源
      最近更新 更多