【问题标题】:Parsing field name with a colon in JSON在 JSON 中用冒号解析字段名称
【发布时间】:2014-02-28 07:52:30
【问题描述】:

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

{
  "dc:creator":"Jordan, Micheal",
  "element:publicationName":"Applied Ergonomics",
  "element:issn":"2839749823"
}

事实上,我想知道如何使用 restsharp 之类的库来进行映射?

【问题讨论】:

    标签: c# .net json


    【解决方案1】:

    使用Json.Net

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

    Console.WriteLine(JObject.Parse(json)["dc:creator"]);
    

    【讨论】:

    • +1 非常好的答案,请注意:您违反了 .NET 的命名约定(即属性应该是 PascalCased)
    • 有没有注解映射类名?就像我们对字段所做的那样。
    • 有一个带破折号 (-) 的字段名称我该如何反序列化,在 csharp 中是不可能的。
    • @SerhatKoroglu 为:做你的事
    • @L.B 您的解决方案运行良好..但是当我从 json 字符串中获取整数时,它返回零,请帮助
    【解决方案2】:

    如果您使用DataContractJsonSerializerDataMemberAttribute 具有属性Name,可用于覆盖默认名称。这意味着当您反序列化属性dc:creator 的json 值时,将分配给Publication::Creator 属性,反之,当您序列化C# 对象时。

    例如:

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

    如果您选择使用Json.Net,@L.B 的答案就是要走的路。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-11-07
      • 2016-01-28
      • 2021-11-02
      • 2015-09-09
      • 1970-01-01
      • 2014-09-28
      • 2011-12-22
      相关资源
      最近更新 更多