hello
hello

Reputation: 1228

Is there a way to change Property Name in JSON data

Is there a way I can change the column/property name I'm returning from a JSON response through a Web API ?

Sample JSON response:

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

I tried using Data Annotation on the Model, but, it doesn't seem to achieve what I want

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

Upvotes: 1

Views: 2041

Answers (2)

Phil Cooper
Phil Cooper

Reputation: 3123

You could simply have a new property with the desired name that simply returns data from the other property. Then hide/ignore the other:

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

public string GenericName
{
    get
    {
        return ActualPropName1;
    }
}

Although from your example this won't work for property names like 'Generic Name'.

Upvotes: 2

Safal Mahat
Safal Mahat

Reputation: 90

You can use JSON.NET's JsonProperty

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

Upvotes: 1

Related Questions