hyde
hyde

Reputation: 2585

Json.Net Resolving Property Names Properly

I am getting some data that looks like below JSON from an API

{
    body_html: "<h1>Test</h1>",
    id: "cu1bpkz",
    link_id: "d3_3kkgis",
    author: "jdoe",
    author_flair_text: null,
    author_flair_css_class: null,
    parent_id: "t3_3kkgis",
    body: "Test",
    subreddit_id: "q5_39vkz",
    created_utc: 1442108087,
    subreddit: "test"
}

And here is my Strongly-typed class that I use for deserialization:

public class Comment
{
    public string AuthorFlairText { get; set; }
    public string AuthorFlairCssClass { get; set; }
    public string Author { get; set; }
    public string LinkId { get; set; }
    public string Id { get; set; }
    public string BodyHtml { get; set; }
    public string Url { get; set; }
    public string SubredditId { get; set; }
    public string Subreddit { get; set; }
    public long CreatedUtc { get; set; }
    public string Body { get; set; }
    public string ParentId { get; set; }
}

This is my resolver for resolving the property names:

public class ApiContractResolver : DefaultContractResolver
    {
        protected override string ResolvePropertyName(string propertyName)
        {
            var parts = propertyName.Split(new string[] { "_" }, StringSplitOptions.RemoveEmptyEntries);
            return parts.Select(x => char.ToUpper(x[0]) + x.Substring(1)).Aggregate((curr, next) => curr + next);
        }
    }

This is how I deserializing my JSON and it does not work.

var settings = new JsonSerializerSettings { ContractResolver = new ApiContractResolver() };
var obj = JsonConvert.DeserializeObject<Comment>(json, settings);

While simple properties like body and id get properly converted, more complex properties with _ in the prop name do not. What am I missing?

Upvotes: 1

Views: 1152

Answers (2)

Mohit S
Mohit S

Reputation: 14064

You can try this. you can use JsonPropertyAttribute to tell Json.Net what the property's corresponding json field is.

public class Comment
{
    [JsonProperty("author_flair_text")]
    public string AuthorFlairText { get; set; }

    [JsonProperty("author_flair_css_class")]
    public string AuthorFlairCssClass { get; set; }

    [JsonProperty("author")]
    public string Author { get; set; }

    [JsonProperty("link_id")]
    public string LinkId { get; set; }

    [JsonProperty("id")]
    public string Id { get; set; }

    [JsonProperty("body_html")]
    public string BodyHtml { get; set; }

    [JsonProperty("url")]
    public string Url { get; set; }

    [JsonProperty("subreddit_id")]
    public string SubredditId { get; set; }

    [JsonProperty("subreddit")]
    public string Subreddit { get; set; }

    [JsonProperty("created_utc")]
    public long CreatedUtc { get; set; }

    [JsonProperty("body")]
    public string Body { get; set; }

    [JsonProperty("parent_id")]
    public string ParentId { get; set; }
}

Everything else has been taken care only URL is the property which I cannot find in the JSON. Please have a look else the code is ready to get copy paste and run.

you could store an object of type JsonModel and in your model's constructor initialize it using JsonConvert.DeserializeObject<T>. Your public properties could then just call into that JsonModel instance and get the appropriate values.

Upvotes: 3

Philippe Par&#233;
Philippe Par&#233;

Reputation: 4418

Use the JsonPropertyAttribute like so:

[JsonProperty("author_flair_text")]
public string AuthorFlairText { get; set; }

This ensures it'll take the right name, different from the property in code.

Edit: You can also use this tool for larger json files, it generates classes for your data: http://json2csharp.com/

Upvotes: 1

Related Questions