Is possible optimize json.net schema with JSchemaValidatingReader to deserialize in object in same read of stream?

我与影子孤独终老i 提交于 2019-12-13 00:05:32

问题


I'm trying a poc. Is possible optimize json.net schema with JSchemaValidatingReader to deserialize in object in same read of stream?

In otherworld

string schemaJson = @"{
      'description': 'A person',
      'type': 'object',
      'properties': {
        'name': {'type': 'string'},
        'hobbies': {
          'type': 'array',
          'items': {'type': 'string'}
        }
      }
    }";

JSchema schema = JSchema.Parse(schemaJson);

using (StreamReader s = File.OpenText(@"c:\bigdata.json"))
using (JSchemaValidatingReader reader = new JSchemaValidatingReader(new JsonTextReader(s)))
{
    reader.Schema = schema;
    reader.ValidationEventHandler += (sender, args) => { Console.WriteLine(args.Message); };

    //Deserialize json while validating
    while (reader.Read())
    {
    }
}

thanks


回答1:


Yes, JSchemaValidatingReader is a subclass of JsonReader, so you can use it to deserialize by passing it to JsonSerializer.Deserialize(JsonReader):

using (var s = File.OpenText(@"c:\bigdata.json"))
using (var baseReader = new JsonTextReader(s))
using (var reader = new JSchemaValidatingReader(baseReader))
{
    reader.Schema = schema;
    reader.ValidationEventHandler += (sender, args) => { Console.WriteLine(args.Message); };

    root = JsonSerializer.CreateDefault().Deserialize<RootObject>(reader);
}

Demo fiddle here.

Related documentation: Validate JSON with JSchemaValidatingReader.



来源:https://stackoverflow.com/questions/40306330/is-possible-optimize-json-net-schema-with-jschemavalidatingreader-to-deserialize

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!