0

Currently I am building some functionality that takes an object (in my case a blog post) in JSON format and validates it meets the 'Post' schema before deserializing it into an object. This is my current solution -

    {

        const string rawPost = @"{
        ""userId"": 1,
        ""id"": 200,
        ""title"": ""hello"",
        ""body"": ""body""
    }";

        JSchemaGenerator generator = new JSchemaGenerator();
        JSchema schema = generator.Generate(typeof(Post));

        var isPost = IsValid(JObject.Parse(rawPost), schema);

        if (isPost)
        {
            var post = JsonConvert.DeserializeObject<Post>(rawPost);

        }

    }
    public static bool IsValid(JObject jObject, JSchema jSchema)
    {
        return jObject.IsValid(jSchema);
    }

    public class Post
    {
        public int userId { get; set; }
        public int id { get; set; }
        public string title { get; set; }
        public string body { get; set; }
    }


}

Currently I do not like the fact that my 'Post' object in this case has incorrectly cased properties and breaks normal conventions - Which means the object is not very reusable. Is there another way of achieving the same thing with Pascal Casing?

Ling
  • 25
  • 1
  • 5

1 Answers1

1

You could decorate the properties of your class with the NewtonSoft JsonProperty attribute, setting the PropertyName as follows:

using Newtonsoft.Json;
public class Post
{
    [JsonProperty(PropertyName = "userId")]
    public int UserId { get; set; }
    [JsonProperty(PropertyName = "id ")]
    public int Id { get; set; }
    [JsonProperty(PropertyName = "title ")]
    public string Title { get; set; }
    [JsonProperty(PropertyName = "body ")]
    public string Body { get; set; }
}

The JsonSerializer object will use these in its deserialization.

Edit: or as per the linked duplicate question

Chris Pickford
  • 8,642
  • 5
  • 42
  • 73