-1

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.

4

1 回答 1

0

我想我找到了答案,这比我预期的要简单得多。它只是使用类似的东西:

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

...其中MyNamespace是生成的 C# 类的命名空间,MyNamespace.Anonymous是对应于模式根的类(默认名称来自NJsonSchema),以及jsonString要解析的字符串。

我认为解决方案需要具有模式感知能力,因为它需要了解从模式创建的所有类,但我想它通过反映Anonymous它给出的类以及它的属性在哪里“解决了这个问题”课程,反思那些等等。

问题是我想多了!

于 2020-10-05T15:39:01.870 回答