ASP.NET MVC C# - 显示类属性名称而不是来自 JSON 的属性名称

问题描述

在使用 JsonPropertyAttribute 反序列化从 API 获取的 JSON 对象后遇到困难

我成功地从 JSON 对象中获取了值

{
    "property name": "property value"
}

但我的问题是,而不是像这样显示类属性:

{
    "propertyName": "property value"
}

我只看到我正在获取的 JSON 中的属性名称:

{
    "property name": "property value"
}

有没有一种简单的方法可以让它显示类对象的属性名称,而不是我从 JSON 中获取的属性名称?

编辑:

这是类的外观:

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

我做了一些类似于这个例子的事情:

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");
    }
}

我希望实现的响应是使其像这样的输出:

{
    "propertyName": "property value"
}

解决方法

只需从类中删除 JsonProperty 并在反序列化对象之前将“属性名称”替换为“属性名称”

    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");
    }

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...