Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Parsing field name with a colon in JSON

Tags:

json

c#

.net

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?

like image 799
Serhat Koroglu Avatar asked Feb 28 '14 07:02

Serhat Koroglu


People also ask

Is Colon allowed in JSON?

In the JSON data format, the keys must be enclosed in double quotes. The key and value must be separated by a colon (:) symbol. There can be multiple key-value pairs.

What does colon mean at JSON?

Separator. Double colon ( :: ) is used as a seperator for nested JSON arrays.

How do I parse a string in JSON?

Example - Parsing JSONUse the JavaScript function JSON.parse() to convert text into a JavaScript object: const obj = JSON.parse('{"name":"John", "age":30, "city":"New York"}'); Make sure the text is in JSON format, or else you will get a syntax error.

What is JSONPath parse?

JSONPath is an expression language to parse JSON data. It's very similar to the XPath expression language to parse XML data. The idea is to parse the JSON data and get the value you want. This is more memory efficient because we don't need to read the complete JSON data.


2 Answers

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"]);
like image 58
L.B Avatar answered Sep 30 '22 16:09

L.B


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.

like image 29
Leri Avatar answered Sep 30 '22 15:09

Leri