【问题标题】:ASP.NET MVC C# - Display class property names instead of the property names from JSONASP.NET MVC C# - 显示类属性名称而不是 JSON 中的属性名称
【发布时间】:2021-07-23 19:50:33
【问题描述】:

在使用 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"
}

【问题讨论】:

  • 您在哪里查看属性名称? JSON 保持不变。班级保持不变。您是否再次序列化该类并查看原始属性名称?如果您已将它们标记为 [JsonProperty("property name")],这是有道理的,因为这会告诉序列化程序在 JSON 中使用该名称,两种方式。
  • 你能复制一下你的类的结构吗
  • 第二个代码块" property value"的第一个空格是错字吗?
  • 我尝试了写在该链接中的答案,但发生在我身边的是,它根本没有获取 json 属性的值。

标签: c# json asp.net-mvc jsonconvert


【解决方案1】:

只需从类中删除 JsonProperty 并在反序列化对象之前将“property name”替换为“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");
    }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-04-28
    • 2015-03-31
    • 1970-01-01
    • 1970-01-01
    • 2011-07-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多