反序列化时如何检查JSON字符串中是否存在属性

我有这个反序列化 JSON 字符串的代码。

现在我们可以看到 JSON 字符串具有例如以下属性:(请注意 CORS 属性存在于“has”属性下,因此我们需要在我相信之前检查“has”是否也存在)


CORS


我的问题是。有时,JSON 字符串中可能会缺少此属性。正如所见,我在使用 try/catch 块的地方使用下面的代码。因为如果缺少 CORS 属性,我会得到一个异常,但异常的性能非常昂贵,现在我在 30 个属性上使用 try/catch 块。


然后我想知道如果 CORS 属性首先存在,我们如何检查代码?当 CORS 不存在时,下面的代码行 WITHOUT try/catch 会给出此错误:


无法对空引用执行运行时绑定


String corsvalue = "";

try { corsvalue = deserializedTicker.has.CORS.ToLower(); } catch { }

JSON字符串:


  "id": "hello", 

  "name": "Hello",

  "has": { 

    "CORS": false,

    "CORS2": true

  },

  "has2": { 

    "CORS3": false,

    "CORS4": true

  }

}

完整代码:


String JSONstring = "{ \"id\": \"hello\", \"name\": \"Hello\", \"has\": { \"CORS\": false, \"CORS2\": true }, \"has2\": { \"CORS3\": false, \"CORS4\": true } }\";"


var deserializedTicker = JsonConvert.DeserializeObject<JsonInfo>(JSONstring);


String corsvalue = "";

try { corsvalue = deserializedTicker.has.CORS.ToLower(); } catch { }



public class JsonInfo 

{

  public string id { get; set; }

  public string name { get; set; }

  public JsonHasInfo has { get; set; }

  public JsonHas2Info has2 { get; set; }

}


public class JsonHasInfo

{

  public bool CORS { get; set; }

  public bool CORS2 { get; set; }

}


public class JsonHas2Info

{

  public bool CORS3 { get; set; }

  public bool CORS4 { get; set; }

}


jeck猫
浏览 153回答 1
1回答

慕容708150

干得好:String JSONstring = "{ \"id\": \"hello\", \"name\": \"Hello\", \"has\": { \"CORS\": false, \"CORS2\": true }, \"has2\": { \"CORS3\": false, \"CORS4\": true }}";&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; JObject jobject = JObject.Parse(JSONstring);&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; JToken cors = jobject.SelectToken("has.CORS");&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; if (cors != null)&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; JsonInfo myEvent = jobject.ToObject<JsonInfo>();&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }
打开App,查看更多内容
随时随地看视频慕课网APP