0

Given a JSON schema (given at runtime), I need a function in C# that takes a string as an argument, validates if the given string is a valid JSON object of the given schema and returns a C# serializable object.

With C# serializable object I mean an object that can be added to a ValueSet.

Problem 1: I know, with Json.NET I can deserialize JSON objects, but this works only with classes that are defined at compilation time, whereas my JSON schema is given at runtime, so the classes are not already defined at compilation time!

Problem 2: Json.NET is not returning serializable objects, i.e. the objects that are returned by Json.NET can not be added to a ValueSet!

Community
  • 1
  • 1
user9514066
  • 119
  • 1
  • 11
  • what do you need by value set what do you really want can you show some sample example – Usman Asif Jan 19 '20 at 15:06
  • You can try to use `dynamic` object for that – Pavel Anikhouski Jan 19 '20 at 15:07
  • No, jsom.net doesnt only deserialize to c# classes, it deserialize to dynamic object as well that gives you JObject, Jtoken or others like JTokens you can go through – Jawad Jan 19 '20 at 15:40
  • [Dynamically deserialize](https://stackoverflow.com/a/9326146/1390548) – Jawad Jan 19 '20 at 15:41
  • Nice, thanks! But these dynamically generated types still can not be added to a ValueSet! – user9514066 Jan 19 '20 at 15:54
  • In addition, the method IsValid(Schema) can not be called when parsed dynamically – user9514066 Jan 19 '20 at 16:35
  • You could deserialize to `JToken` using `JSchemaValidatingReader` as shown in [Is possible optimize json.net schema with JSchemaValidatingReader to deserialize in object in same read of stream?](https://stackoverflow.com/a/40312384/3744182), then convert the resulting `JToken` hierarchy to `[Serializable]` c# objects by using `JsonHelper.ToObject()` from [this answer](https://stackoverflow.com/a/19140420/3744182) to [How do I use JSON.NET to deserialize into nested/recursive Dictionary and List?](https://stackoverflow.com/q/5546142/3744182). Is that what you want? – dbc Jan 19 '20 at 18:09
  • Alternatively, why not store the raw JSON as a string? Once it has passed validation you know it's OK. – dbc Jan 19 '20 at 19:33

1 Answers1

0

While it doesn't exactly solve your problems, there may be a workaround: composition.

Create a wrapper class that implements ISerializable and has a dynamic property. Deserialize your object and store it in this property. You'll have to supply the de/serialization code for your object, but that should be straightforward: just have the JSON serializer do the work.

The trouble you're experiencing is that you're asking a library that's written as generically as possible to do something very specific. You'd have a hard time finding a library that does this. (Though I think it's a good idea, and I may add it to my type generation feature.)


(Shameless plug) Also, have you looked at Manatee.Json?

gregsdennis
  • 7,218
  • 3
  • 38
  • 71