在C#中验证JSON模式 - 有更好的方法吗?

时间:2018-04-27 15:02:30

标签: c# json json.net

目前我正在构建一些以JSON格式获取对象(在我的案例中是博客文章)的功能,并验证它是否符合' Post'在将其反序列化为对象之前的模式。这是我目前的解决方案 -

    {

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


}

目前我不喜欢我的帖子&#39;在这种情况下,对象具有错误的外壳属性并且违反了正常约定 - 这意味着该对象不是非常可重用的。是否有其他方法可以与Pascal Casing实现相同的目标?

1 个答案:

答案 0 :(得分:1)

您可以使用NewtonSoft JsonProperty属性修饰类的属性,将PropertyName设置如下:

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

JsonSerializer对象将在其反序列化中使用这些。

编辑:或根据链接的重复问题

相关问题