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

前端 未结 3 614
故里飘歌
故里飘歌 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.
    }
    
    0 讨论(0)
  • 2020-12-16 12:02

    Or you can simply use the ContainsKey on a JsonObject. Here is a sample of my own code with similar problem to yours:

    foreach (JsonObject feed in data)
                {
                    var fbFeed = new FacebookFeeds();
                    if (feed.ContainsKey("message"))
                        fbFeed.Message = (string)feed["message"];
                    if (feed.ContainsKey("story"))
                        fbFeed.Message = (string)feed["story"];
                    if (feed.ContainsKey("picture"))
                        fbFeed.Message = (string)feed["picture"];
                    fbFeeds.Add(fbFeed);
                }
    
    0 讨论(0)
  • 2020-12-16 12:06

    You can use the TryGetValue it's kinda a standard method for doing exactly what you need. I say standard because the Try methods can be found all around the .NET framework and have generally always the same method signature.

    Using that you can get the value like this.

    JObject json = new JObject();
    JToken value;
    if (json.TryGetValue("myProperty", out value))
    {
        string finalValue = (string)value;
    }
    

    The TryGetValue return a boolean telling whether the value was found or not, if the value is found the value passed as second parameter is setted to the property value. Otherwise is setted to null.

    0 讨论(0)
提交回复
热议问题