Click here to Skip to main content
15,891,633 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I am using Newtonsoft library JSchema to check schema of a json response. but my check is coming back false. I have created a class with the objects present in the API json response and then generated the class object to schema using JSchemaGenerator library. After that I parsed using JArray and used IsValid method to check if schema is valid but its returning false. My response is a list but I want to keep my class objects as is and just want to check if id is long, name is string and type is long. Also keeping IsJsonValid method as generic as possible.

The response is coming as Array of Objects.. is their a way to just check the properties data type if you define it just in the class Schema like I did.

What I have tried:

public class Schema
    {
        public long id { get; set; }
        public string name { get; set; }
        public long type { get; set; }

   }
//json respone from the API
[
   {
    "id": 1,
    "name": "name1",
    "type": 0
   },
  {
    "id" : 2
    "name" : "name2",
    "type" : 1
  }

]
//here is the method to check if JsonIsValid

 public static bool IsJsonValid<TSchema>(this string value)
        {
            bool res = true;
            var obj = JsonConvert.DeserializeObject<List<TSchema>>(value);
           
            JSchemaGenerator generator = new JSchemaGenerator();
            JSchema schema = generator.Generate(typeof(TSchema));
                              
            JArray actualJson = JArray.Parse(value);
            bool valid = actualJson.IsValid(schema);
          
            return valid;
        }


//usage:
string json  = "[{\"id\":1,\"name\":\"name1\",\"type\":0},{\"id\":2,\"name\":\"name2\",\"type\":1}]";
  bool isValid = json.IsJsonValid<Schema>();
Posted
Updated 29-Jul-20 20:05pm

1 solution

If I run your JSON through a class generator (I use Convert JSON to C# Classes Online - Json2CSharp Toolkit[^]) it does say it's invalid: and it is.
Your API is returning bad JSON - specifically, this line:
"id" : 2
requires a terminating comma. Add that, and it starts to work:
[
   {
    "id": 1,
    "name": "name1",
    "type": 0
   },
  {
    "id" : 2,
    "name" : "name2",
    "type" : 1
  }

]
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900