5

How can we parse if json fields contains a colon(:)? Like this:

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

In fact I wonder how to do this with a library like restsharp, for mapping?

Darkzaelus
  • 2,059
  • 1
  • 15
  • 31
Serhat Koroglu
  • 1,263
  • 4
  • 19
  • 41

2 Answers2

21

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

OR

Console.WriteLine(JObject.Parse(json)["dc:creator"]);
L.B
  • 114,136
  • 19
  • 178
  • 224
3

If you use DataContractJsonSerializer, DataMemberAttribute has property Name which can be used to override default name. This means that when you deserialize json value of property dc:creator is assigned to Publication::Creator property and on the contrary when you serialize C# object.

For example:

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

If you choose to use Json.Net, @L.B's answer is the way to go.

Leri
  • 12,367
  • 7
  • 43
  • 60