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?
ResolvePropertyNamemaps from the c# property name to the JSON property name. You're going in the wrong direction. For an example, see CamelCasePropertyNamesContractResolver.cs.