Deserialize json in a “TryParse” way

后端 未结 6 641
走了就别回头了
走了就别回头了 2020-11-28 09:14

When I send a request to a service (that I do not own), it may respond either with the JSON data requested, or with an error that looks like this:

{
    \"er         


        
6条回答
  •  被撕碎了的回忆
    2020-11-28 09:33

    With Json.NET you can validate your json against a schema:

     string schemaJson = @"{
     'status': {'type': 'string'},
     'error': {'type': 'string'},
     'code': {'type': 'string'}
    }";
    
    JsonSchema schema = JsonSchema.Parse(schemaJson);
    
    JObject jobj = JObject.Parse(yourJsonHere);
    if (jobj.IsValid(schema))
    {
        // Do stuff
    }
    

    And then use that inside a TryParse method.

    public static T TryParseJson(this string json, string schema) where T : new()
    {
        JsonSchema parsedSchema = JsonSchema.Parse(schema);
        JObject jObject = JObject.Parse(json);
    
        return jObject.IsValid(parsedSchema) ? 
            JsonConvert.DeserializeObject(json) : default(T);
    }
    

    Then do:

    var myType = myJsonString.TryParseJson(schema);
    

    Update:

    Please note that schema validation is no longer part of the main Newtonsoft.Json package, you'll need to add the Newtonsoft.Json.Schema package.

    Update 2:

    As noted in the comments, "JSONSchema" have a pricing model, meaning it isn't free. You can find all the information here

提交回复
热议问题