如何反序列化在键名.Net中包含点(.)的Json字符串 [英] how to deserialize a Json string that contain dot (.) in key name .Net

查看:22
本文介绍了如何反序列化在键名.Net中包含点(.)的Json字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

{
     "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,
             }]
    
}

这是我的 Json 字符串的一个例子,我不能更改它的键名吗?提前致谢.

this is an example of my Json string i cant change its key names any sugestion? thanks in advance.

推荐答案

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

Depending on the library you are using for deserialization you can mark model fields with corresponding attributes - for example JsonPropertyNameAttribute for System.Text.Json or JsonPropertyAttribute for 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);

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

这篇关于如何反序列化在键名.Net中包含点(.)的Json字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆