有没有办法在JSON数据中更改属性名称

时间:2016-12-18 04:26:56

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

有没有办法可以更改列/属性名称我是通过Web API从JSON响应中返回的?

示例JSON响应:

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

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

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

2 个答案:

答案 0 :(得分:2)

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

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

public string GenericName
{
    get
    {
        return ActualPropName1;
    }
}

虽然从你的例子来看,这对于像“通用名称”这样的属性名称不起作用。

答案 1 :(得分:0)

您可以使用JSON.NET的JsonProperty

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