如果json字段包含冒号(:),我们如何解析?就像这样:
{ "dc:creator":"Jordan, Micheal", "element:publicationName":"Applied Ergonomics", "element:issn":"2839749823"}
{
"dc:creator":"Jordan, Micheal",
"element:publicationName":"Applied Ergonomics",
"element:issn":"2839749823"
}
事实上,我想知道如何用像restsharp这样的库来做Map?
ou6hu8tu1#
使用Json.Net
string json = @"{ ""dc:creator"":""Jordan, Micheal"", ""element:publicationName"":""Applied Ergonomics"", ""element:issn"":""2839749823"" }";var pub = JsonConvert.DeserializeObject<Publication>(json);
string json = @"{
""dc:creator"":""Jordan, Micheal"",
""element:publicationName"":""Applied Ergonomics"",
""element:issn"":""2839749823""
}";
var pub = JsonConvert.DeserializeObject<Publication>(json);
public class Publication{ [JsonProperty("dc:creator")] public string creator { set; get; } [JsonProperty("element:publicationName")] public string publicationName { set; get; } [JsonProperty("element:issn")] public string issn { set; get; }}
public class Publication
[JsonProperty("dc:creator")]
public string creator { set; get; }
[JsonProperty("element:publicationName")]
public string publicationName { set; get; }
[JsonProperty("element:issn")]
public string issn { set; get; }
或
Console.WriteLine(JObject.Parse(json)["dc:creator"]);
pbossiut2#
如果你使用DataContractJsonSerializer,DataMemberAttribute有一个属性Name,可以用来覆盖默认名称。这意味着当你序列化json时,属性dc:creator的值被分配给Publication::Creator属性,相反,当你序列化C#对象时。举例来说:
DataContractJsonSerializer
DataMemberAttribute
Name
dc:creator
Publication::Creator
public class Publication{ [DataMember(Name="dc:creator")] public string Creator { set; get; } [DataMember(Name="element:publicationName")] public string PublicationName { set; get; } [DataMember(Name="element:issn")] public string Issn { set; get; }}
[DataMember(Name="dc:creator")]
public string Creator { set; get; }
[DataMember(Name="element:publicationName")]
public string PublicationName { set; get; }
[DataMember(Name="element:issn")]
public string Issn { set; get; }
如果你选择使用Json.Net,@L.B的答案是正确的。
Json.Net
cuxqih213#
由于Newtonsoft已被弃用,因此最好使用JsonPropertyName属性(特别是在.Net Core中,它是本机属性)而不是JsonProperty。因此,它可能看起来像:
JsonPropertyName
JsonProperty
public class Publication{ [JsonPropertyName("dc:creator")] public string Creator { set; get; } [JsonPropertyName("element:publicationName")] public string PublicationName { set; get; } [JsonPropertyName("element:issn")] public string Issn { set; get; }}
[JsonPropertyName("dc:creator")]
[JsonPropertyName("element:publicationName")]
[JsonPropertyName("element:issn")]
另外请注意,与[DataMember]相反,如果它进行Restsharp的格式化,它也适用于集合属性(JSON数组)。
[DataMember]
Restsharp
3条答案
按热度按时间ou6hu8tu1#
使用Json.Net
或
pbossiut2#
如果你使用
DataContractJsonSerializer
,DataMemberAttribute
有一个属性Name
,可以用来覆盖默认名称。这意味着当你序列化json时,属性dc:creator
的值被分配给Publication::Creator
属性,相反,当你序列化C#对象时。举例来说:
如果你选择使用
Json.Net
,@L.B的答案是正确的。cuxqih213#
由于Newtonsoft已被弃用,因此最好使用
JsonPropertyName
属性(特别是在.Net Core中,它是本机属性)而不是JsonProperty
。因此,它可能看起来像:另外请注意,与
[DataMember]
相反,如果它进行Restsharp
的格式化,它也适用于集合属性(JSON数组)。