Pecheneg
Pecheneg

Reputation: 808

How to ensure that the class library represents the Json Schema perfectly

I have a JSON Schema, and a class library. I am able to serialize this class, then convert back successfully to object. To test it, I create a random object, serialize it. Then convert to object and check its validity. And deserialize it just to be sure about the values.

The code below works perfectly - but I want to be absolutely sure that the class library represents the Json Schema.

Is there a way to achieve this? I found some online tools tries to create the class library from given schema, but none of them were so useful.

  // Create random object.
  MyObject myObject = new MyObject().CreateRandomMyObject();
  // Serialize it.
  string JSONObjectText = JsonConvert.SerializeObject(myObject);

  // Check if schema is valid.
  JSchema schema = JSchema.Parse(txtSchema.Value);

  // Check if the serialized object is valid for schema.
  JObject jsonObject = JObject.Parse(JSONObjectText);
  IList<string> errorMessages;
  bool valid = jsonObject.IsValid(schema, out errorMessages);

  // Check if the serialized object can be deserialized.
  MyObject myObjectReDeserialized = (MyObject)JsonConvert.DeserializeObject(JSONObjectText, typeof(MyObject), new JsonSerializerSettings() { MissingMemberHandling = MissingMemberHandling.Error });

Upvotes: 0

Views: 129

Answers (1)

A way to do test-oriented assertion of your mapping is to use FsCheck to generate plenty of random objects and then assert what you want to hold from them: in this case, that

  • their serialization is valid given the schema,
  • they can be deserialized back to the same object. (You should make sure you are using structural equality there.)

To be precise, such approach only checks that everything described by your objects is representable by the schema. You might want to do the other way also -- that every JSON that conforms to the schema is representable by your objects. Again, you can generate many possible JSONs conforming to the schema and check that

  • they can be deserialized to your objects,
  • reserialization of those objects gives you the same JSON you started with.

Beware though, this might not be practical: FsCheck probably don't have some nice, first-class support for JSON schema based generation out-of-the-box.

If the schema you have is going to change in the future, it would be really great to have a way to generate corresponding objects to have strong types even at the boundary of your application. Have you tried Swagger Codegen? Swagger describes it's endpoints using subset of JSON Schema. The corresponding tooling might help you.

Upvotes: 2

Related Questions