Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Deserializing JSON responses which contain attributes that conflict with keywords

Tags:

json

c#

json.net

There is an API which I don't control, but whose output I need to consume with C#, preferably using JSON.Net.

Here's an example response:

[
    {
        "media_id": 36867, 
        "explicit": 0
    }
]

I had planned to have a class like so:

class Media {
    public int media_id;
    public int explicit;
}

And to deserialize:

var l = JsonConvert.DeserializeObject<List<Media>>(s);

Unfortunately, "explicit" is a C# keyword, so this can't compile.

My next guess is to modify the class:

class Media {
    public int media_id;
    public int explicit_;
}

... and somehow map the response attributes to the C# attributes.

How should I do that, or am I totally going at this the wrong way?

Failing that, I'd be OK to just plain ignore the "explicit" in the response, if there's a way to do that?

like image 418
Jeremy Dunck Avatar asked Jan 12 '11 16:01

Jeremy Dunck


2 Answers

C# lets you define members with reserved word names (for interoperability cases exactly like this) by escaping them with an @, e.g.,

class Media {
    public int media_id;
    public int @explicit;
}

Not sure how this plays with JSON.Net, but I would imagine it should work (since the @ is an escape and not actually part of the field name).

like image 79
Eric Rosenberger Avatar answered Oct 06 '22 00:10

Eric Rosenberger


Haven't used JSON.Net, but judging by the docs here, I figure you just need to do what you'd do with XmlSerialization: Add an attribute to tell how the JSON property should be called:

class Media {
    [JsonProperty("media_id")]
    public int MediaId;
    [JsonProperty("explicit")]
    public int Explicit;
}
like image 34
Robert Giesecke Avatar answered Oct 05 '22 23:10

Robert Giesecke