如何反序列化键名.Net中包含点(.)的Json字符串

som*_*one 0 c# json .net-core

{
     "odata.metadata": "sometext",
     "odata.nextLink": "sometext",
    "value": [{
            "odata.type": "SP.Data.RegionsListItem",
            "odata.id": "07404daa-61b5-4947-af9f-38f29822f775",
            "odata.etag": "\"3\"",
            "odata.editLink": "Web/Lists(guid'65dc896b-df87-4145-98d9-57c7ea619e66')/Items(3)",
            "FileSystemObjectType": 0,
            "Id": 3,
            "ServerRedirectedEmbedUri": null,
             }]
    
}
Run Code Online (Sandbox Code Playgroud)

这是我的 Json 字符串的示例,我无法更改其键名,有什么建议吗?提前致谢。

Gur*_*ron 6

根据您用于反序列化的库,您可以使用相应的属性标记模型字段 - 例如JsonPropertyNameAttributeforSystem.Text.JsonJsonPropertyAttributefor Newtonsoft.Json

Newtonsoft.Json:

public class Root
{
    [JsonProperty("odata.metadata")]
    public string OdataMetadata { get; set; }

    [JsonProperty("odata.nextLink")]
    public string OdataNextLink { get; set; }

    [JsonProperty("value")]
    public List<Value> Value { get; set; } // do the same for Value type
}

 var result = JsonConvert.DeserializeObject<Root>(json);
Run Code Online (Sandbox Code Playgroud)

System.Text.Json:

public class Root
{
    [JsonPropertyName("odata.metadata")]
    public string OdataMetadata { get; set; }

    [JsonPropertyName("odata.nextLink")]
    public string OdataNextLink { get; set; }

    [JsonPropertyName("value")]
    public List<Value> Value { get; set; }
}


var result = JsonSerializer.Deserialize<Root>(json);
Run Code Online (Sandbox Code Playgroud)


归档时间:

查看次数:

1268 次

最近记录:

4 年,9 月 前