11

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?

Jeremy Dunck
  • 5,724
  • 6
  • 25
  • 30

3 Answers3

19

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;
}
shanethehat
  • 15,460
  • 11
  • 57
  • 87
Robert Giesecke
  • 4,314
  • 21
  • 22
  • Cheers, I skipped over that one because the ToC said "serialization" when I wanted deserialization. Thanks for the pointer. – Jeremy Dunck Jan 12 '11 at 17:06
12

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).

Eric Rosenberger
  • 8,987
  • 1
  • 23
  • 24
  • I understand what you're saying, but can you provide a link to further explanation? I tried this w/ that change: "var x = new Media(); x.explicit = true;" Wouldn't compile, but "x.@explicit = true" did. – Jeremy Dunck Jan 12 '11 at 17:03
  • In your code, you would use "@explicit". But this gets compiled to an actual name of "explicit" in the binary. So the JSON.Net serialization/deserialization code would see "explicit", not "@explicit". Just like when you use "\n" in your code, but it gets compiled into a linefeed in the binary. – Eric Rosenberger Jan 12 '11 at 17:32
  • I see, thanks. Still accepted the JsonProperty answer, since it is specific to this domain and handles more general cases as well. – Jeremy Dunck Jan 12 '11 at 17:55
1

The following code worked for me.

class JsonRpc {
  public string id;
  public string method;
  public string[] @params;
}
JsonConvert.DeserializeObject<JsonRpc> (data)

Thanks everyone