当前位置: 动力学知识库 > 问答 > 编程问答 >

json.net - c# - check for null in a collection initializer

问题描述:

I am parsing a Json document using Json.NET and creating an ArrayList using a Collection Initializer as follows

var array = new ArrayList

{

inputJson["abc"].ToString(),

inputJson["def"].Value<float>(),

inputJson["ghi"].Value<float>()

};

Now I would like to add a null check so it doesn't throw an exception if one of the properties is missing in the Json document.

Thanks

网友答案:

Something like this would do the trick

var array = new ArrayList
{
      inputJson["abc"] != null ? inputJson["abc"].ToString() : "",
      inputJson["def"] != null ? inputJson["def"].Value<float>() : 0.0F,
      inputJson["ghi"] != null ? inputJson["ghi"].Value<float>() : 0.0F
};
网友答案:

I would create extension methods to handle this. Note, I'm not positive on the types here, so bear with me:

public static string AsString(this JObjectValue jsonValue, string defaultValue = "")
{
    if (jsonValue != null)
        return jsonValue.ToString();
    else
        return defaultValue;
}

public static T As<T>(this JObjectValue jsonValue, T defaultValue = default(T))
{
    if (jsonValue != null)
        return jsonValue.Value<T>();
    else
        return defaultValue;
}

With usage:

var array = new ArrayList
{
    inputJson["abc"].AsString(),
    inputJson["def"].As<float>(),
    inputJson["ghi"].As<float>(),
    inputJson["jkl"].As(2.0f) //or with custom default values and type inference
};

This also has the benefit of avoiding hitting the indexer twice (once to check for null, and a second time to convert the value), and avoids repeating yourself as to how you parse/read the json input.

网友答案:

You can try this :

var array = new ArrayList
{
      inputJson["abc"] ?? inputJson["abc"].ToString(),
      ...
};
分享给朋友:
您可能感兴趣的文章:
随机阅读: