如何解决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");
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。