解析JSON中带冒号的字段名

sy5wg1nm  于 2023-10-21  发布在  其他
关注(0)|答案(3)|浏览(199)

如果json字段包含冒号(:),我们如何解析?就像这样:

  1. {
  2. "dc:creator":"Jordan, Micheal",
  3. "element:publicationName":"Applied Ergonomics",
  4. "element:issn":"2839749823"
  5. }

事实上,我想知道如何用像restsharp这样的库来做Map?

ou6hu8tu

ou6hu8tu1#

使用Json.Net

  1. string json = @"{
  2. ""dc:creator"":""Jordan, Micheal"",
  3. ""element:publicationName"":""Applied Ergonomics"",
  4. ""element:issn"":""2839749823""
  5. }";
  6. var pub = JsonConvert.DeserializeObject<Publication>(json);
  1. public class Publication
  2. {
  3. [JsonProperty("dc:creator")]
  4. public string creator { set; get; }
  5. [JsonProperty("element:publicationName")]
  6. public string publicationName { set; get; }
  7. [JsonProperty("element:issn")]
  8. public string issn { set; get; }
  9. }

  1. Console.WriteLine(JObject.Parse(json)["dc:creator"]);
展开查看全部
pbossiut

pbossiut2#

如果你使用DataContractJsonSerializerDataMemberAttribute有一个属性Name,可以用来覆盖默认名称。这意味着当你序列化json时,属性dc:creator的值被分配给Publication::Creator属性,相反,当你序列化C#对象时。
举例来说:

  1. public class Publication
  2. {
  3. [DataMember(Name="dc:creator")]
  4. public string Creator { set; get; }
  5. [DataMember(Name="element:publicationName")]
  6. public string PublicationName { set; get; }
  7. [DataMember(Name="element:issn")]
  8. public string Issn { set; get; }
  9. }

如果你选择使用Json.Net,@L.B的答案是正确的。

cuxqih21

cuxqih213#

由于Newtonsoft已被弃用,因此最好使用JsonPropertyName属性(特别是在.Net Core中,它是本机属性)而不是JsonProperty。因此,它可能看起来像:

  1. public class Publication
  2. {
  3. [JsonPropertyName("dc:creator")]
  4. public string Creator { set; get; }
  5. [JsonPropertyName("element:publicationName")]
  6. public string PublicationName { set; get; }
  7. [JsonPropertyName("element:issn")]
  8. public string Issn { set; get; }
  9. }

另外请注意,与[DataMember]相反,如果它进行Restsharp的格式化,它也适用于集合属性(JSON数组)。

相关问题