【问题标题】:how to deserialize a Json string that contain dot (.) in key name .Net [duplicate]如何反序列化键名.Net中包含点(。)的Json字符串[重复]
【发布时间】:2021-07-13 16:45:29
【问题描述】:
{
     "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 字符串的一个示例,我无法更改其键名任何建议?提前致谢。

【问题讨论】:

标签: c# json .net-core


【解决方案1】:

根据您用于反序列化的库,您可以使用相应的属性标记模型字段 - 例如,JsonPropertyNameAttribute 表示 System.Text.JsonJsonPropertyAttribute 表示 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);

【讨论】:

  • 谢谢你的工作
  • @someone 很乐意提供帮助!如果答案对您有用,请将其标记为已接受(答案左侧的勾勒勾号)。或者来自 derpirscher 的那个。
【解决方案2】:

为数据创建类时,可以对类成员使用注释。例如,当使用 Newtonsoft.Json 时,它是这样工作的:

class MyData {

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

[JsonProperty("odata.nextlink")]
public string NextLink {get;set;}

... 
}

对于其他库,注释的名称可能不同。还要确保您正在导入正确的命名空间并为您正在使用的库使用正确的注释。即例如 System.Text.Json.JsonPropertyName 注释在使用 Newtonsoft.Json 反序列化时不会产生任何影响,反之亦然。

然后就可以反序列化了

var data = JsonConvert.DeserializeObject<MyData>(thejsonstring);

并使用其 .NET 名称访问该属性

 var metadata = data.Metadata;

【讨论】:

  • 谢谢你的工作
猜你喜欢
  • 2020-09-27
  • 2012-12-09
  • 1970-01-01
  • 2012-05-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多