如何验证 JObject 是否属于特定类型

我需要弄清楚 JObject 是否具有与 CustomObject 类型匹配的正确属性。我使用 JObject.ToObject 希望如果属性与 CustomObject 不匹配它会失败,但它仍然创建所有属性为 null 的 CustomObject。


无论如何,我可以在调用 ToObject 之前验证它吗?


class CustomObject

{

  string fname;

  string lname;

}


void test()

{

  string json = "{\"User\": \"Hello\"}";

  JObject jsonObj = JObject.Parse(json);


  CustomObject custObj = null;



  // this always creates CustomObject instance

  // I need to validate that jsonObj has valid attributes that match CustomObject

  custObj = JObject.ToObject<CustomObject>(); 


胡说叔叔
浏览 179回答 3
3回答

犯罪嫌疑人X

编辑:您可以使用[JsonRequiredAttribute]:class CustomObject{&nbsp; &nbsp; [JsonRequiredAttribute]&nbsp; &nbsp; string fname;&nbsp; &nbsp; [JsonRequiredAttribute]&nbsp; &nbsp; string lname;}或者,您可以使用Newtonsoft.Json.Schema来验证:var schema = JSchema.Parse(@"{&nbsp;&nbsp; &nbsp; 'type': 'object',&nbsp; &nbsp; 'properties': {&nbsp; &nbsp; &nbsp; &nbsp; 'fname': { 'type': 'string' },&nbsp; &nbsp; &nbsp; &nbsp; 'lname': { 'type': 'string' }&nbsp; &nbsp; },&nbsp; &nbsp; 'additionalProperties': false,&nbsp; &nbsp; 'required': ['name', 'email']}");var jsonObj = JObject.Parse("{\"User\": \"Hello\"}");// throws if not validjsonObj.Validate(schema);// or, if you want to handle it yourselfif (!jsonObj.IsValid(schema, out IList<ValidationError> errors)){&nbsp; &nbsp; // ...}// if all passvar custObj = jsonObj.ToObject<CustomObject>();

qq_遁去的一_1

public class CustomObject{&nbsp; &nbsp; [JsonProperty("FirstName")]&nbsp; &nbsp; string fname { get; set; }&nbsp; &nbsp; [JsonProperty("LastName")]&nbsp; &nbsp; string lname { get; set; }}public void Test()&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; Dictionary<string, string> collection = new Dictionary<string, string>();&nbsp; &nbsp; &nbsp; &nbsp; collection.Add("FirstName", "Test");&nbsp; &nbsp; &nbsp; &nbsp; collection.Add("LastName", "1234");&nbsp; &nbsp; &nbsp; &nbsp; JObject jsobObj = JObject.Parse(JsonConvert.SerializeObject(collection, Newtonsoft.Json.Formatting.Indented));&nbsp; &nbsp; &nbsp; &nbsp; CustomObject custObj = new CustomObject();&nbsp; &nbsp; &nbsp; &nbsp; if (jsobObj != null)&nbsp; &nbsp; &nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; if (jsobObj.Property("FirstName") != null && jsobObj.Property("LastName") != null)&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; custObj = jsobObj.ToObject<CustomObject>();&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; }

GCT1015

您可以使用.SelectToken()它从具有多个不同对象的较大 json 中获取特定对象。对于您的具体示例,它看起来像这样。custObj = (CustomObject)jsonObj.SelectToken("CustomObject");您要将所选标记转换为CustomObject,然后将其分配给您的custObj变量。
打开App,查看更多内容
随时随地看视频慕课网APP