Possible to look for Key that does not exist in Json.net

前端 未结 3 615
故里飘歌
故里飘歌 2020-12-16 11:10

I got a couple different formats that come in but I can\'t figure out how to handle them all because when I try to find by key json.net crashes. I was hoping it would just r

3条回答
  •  隐瞒了意图╮
    2020-12-16 12:01

    Assuming that you use Newtonsoft.Json:

    You can use JObject to test if there is a property or not:

    JObject jObj; //initialized somewhere, perhaps in your foreach
    var msgProperty = jObj.Property("msg");
    
    //check if property exists
    if (msgProperty != null) {
        var mag = msgProperty.Value;
    } else {
        //there is no "msg" property, compensate somehow.
    }
    

提交回复
热议问题