ASP.NET MVC C# - Display class property names instead of the property names from JSON

500 Views Asked by At

I'm having difficulty after I Deserialize the JSON object I am getting from an API using JsonPropertyAttribute

I successfully get the value from the JSON object

{
    "property name": "property value"
}

but my problem is, instead of the class property display like so:

{
    "propertyName": "property value"
}

I only see the property names from JSON that I was fetching:

{
    "property name": "property value"
}

Is there an easy way to make it display the property name of the class object instead of the ones from JSON that I fetched?

EDIT:

Here is how the class looks:

public class JsonObjectDto {
    [JsonProperty(PropertyName = "property name")]
    public string propertyName { get; set; }
}

And I do something similar to this example:

public class HomeController : Controller {
    public ActionResult Index() {
        string jsonResponseString = "{\"property name\":\"property value\"}";
        JsonObjectDto result = JsonConvert.Deserialize<JsonObjectDto>(jsonResponseString);
        
        if(result != null) {
            return Ok(result);
        }
        throw new Exception("fetch response error");
    }
}

I am hoping to achieve to the response is to make it like this output:

{
    "propertyName": "property value"
}
1

There are 1 best solutions below

0
On

Simply Remove JsonProperty from class and Before Deserializing Object Replace "property name" with "propertyname"

    public ActionResult Index() 
    {
        string jsonResponseString = "{\"property name\":\"property value\"}";
        jsonResponseString=jsonResponseString.Replace("property name","propertyName");
        JsonObjectDto result = JsonConvert.Deserialize<JsonObjectDto>(jsonResponseString);
                if(result != null) {
            return Ok(result);
        }
        throw new Exception("fetch response error");
    }