我有一个JSON Schema和一个类库。 我可以序列化这个类,然后成功转换回对象。 为了测试它,我创建了一个随机对象,将其序列化。 然后转换为对象并检查其有效性。 并反序列化它只是为了确保值。如何确保类库完美地表示Json Schema
下面的代码完美的作品 - 但 我想是绝对肯定的类库表示JSON模式。
有没有办法做到这一点?我发现一些在线工具试图从给定的模式创建类库,但没有一个是如此有用。
// 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 });
您可以复制你的字符串JSON和过去,它在C#类。 – SeM
@SeM我不明白。是的,我可以将字符串转换为对象。我想要的是确保“JsonSchema = Class Library”。 –