Parse Json into a schema-generated set of classes

482 Views Asked by At

I have a Json schema and can use NJsonSchema.CodeGeneration.CSharp to create classes corresponding to it. So if I have json which conforms to the schema, I should be able to easily parse it into a collection of objects whose classes are the classes generated from the schema?

So how can I do this - parse json and get out C# class objects that correspond to the objects in the json (as define by the schema)?

As an example - if the schema defines a first object definition which is an array of a second object definition, then I would like to be able to parse it in such a way that the output is an instance of the class corresponding to the first object definition and it has a member which is a List of instances of the class corresponding to the second definition. It seems that the schema knows all the information required to do this, so it should be a single line - I appreciate I could do long-hand parsing (eg converting each item in the array) to achieve the same result.

I would think this would be a primary purpose of having C# classes generated from a schema, so what's the magic method I'm missing?

I'm also happy to write C# classes and generate a schema from that if it's a more workable solution.

I've used NJsonSchema but happy to use any other C# json schema and code generation technique that achieves the same end.

UPDATE: After discussion I've seen that if NJsonSchema is used to generate classes from the schema, the TypeScript version of those classes each have a fromJS method which sounds like what I want but they're missing from the C# version. I'm happy to use something other than NJsonSchema to generate classes from schema if it provides a solution.

1

There are 1 best solutions below

0
Richard Hunt On BEST ANSWER

I think I found the answer, which was a lot simpler than I had anticipated. It's simply to use something like:

var ob=JsonConvert.DeserializeObject<MyNamespace.Anonymous>(jsonString);

...where MyNamespace is the namespace of the generated C# classes, MyNamespace.Anonymous is the class corresponding to the root of the schema (default names from NJsonSchema), and jsonString the string to be parsed.

I thought the solution would need to be schema-aware, since it would need to know about all the classes created from the schema, but I guess it 'works that out' from reflecting on the Anonymous class it's given and where the properties of it are classes, reflecting on those and so on.

I was over-thinking the problem!