如何访问Json属性在其名称中有空间

本文关键字:空间 属性 何访问 访问 Json | 更新日期: 2023-09-27 18:17:33

查找json下面的响应…

{
"personalDetails": {
    "Name ": " Taeyeon",
    "Date Of Birth ": " 03/09/1989",
    "Zodiac ": " Pisces"
},
"education": {
    "High School ": " Jeonju Art High school ",
    "University ": " -"
}

}

My Class is here

    public class Biography
{
    public personalDetails personalDetails { get; set; }
    public education education { get; set; }
    public work work { get; set; }
    public personal personal { get; set; }
}

public class personalDetails
{
    public string Name { get; set; }
    public string DateBirth { get; set; }
    public string Zodiac { get; set; }
}
public class education
{
    public string HighSchool { get; set; }
    public string University { get; set; }
}

然后输入代码:

Biography dataSet = JsonConvert.DeserializeObject<Biography>(e.Result);

它不能工作,因为Arttribute有空间。我该怎么办?

如何访问Json属性在其名称中有空间

尝试添加JsonProperty属性。这应该对你有用。

[JsonProperty(PropertyName = "Date Of Birth ")]
public string DateBirth { get; set; }
[JsonProperty(PropertyName = "High School ")]
public string HighSchool { get; set; }

编辑

我看到你也有尾随空格,所以更新了上面的属性。

下载Json作为字符串,并使用类似myString = myString的东西。替换(@"HighSchool","HighSchool")。在反序列化之前执行此步骤。

对于某些人来说这可能是有帮助的:

添加命名空间:using Newtonsoft.Json;

var jsonString = "{" +
    "'personalDetails': {" +
        "'Name ': 'Taeyeon'," +
        "'Date Of Birth ': ' 03/09/1989'," +
        "'Zodiac ': ' Pisces'," +
    "}," +
    "'education': {" +
        "'High School ': ' Jeonju Art High school '," +
        "'University ': ' -'," +
    "}" +
"}";
var json = JsonConvert.DeserializeObject(jsonString);            
return Ok(json);