Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
325 views
in Technique[技术] by (71.8m points)

c# - Deserializing JSON responses which contain attributes that conflict with keywords

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...