Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
750 views
in Technique[技术] by (71.8m points)

c# - Get value from JToken that may not exist (best practices)

What's the best practice for retrieving JSON values that may not even exist in C# using Json.NET?

Right now I'm dealing with a JSON provider that returns JSON that sometimes contains certain key/value pairs, and sometimes does not. I've been using (perhaps incorrectly) this method to get my values (example for getting a double):

if(null != jToken["width"])
    width = double.Parse(jToken["width"].ToString());
else
    width = 100;

Now that works fine, but when there are a lot of them it's cumbersome. I ended up writing an extension method, and only after writing it did I wonder whether maybe I was being stupid... anyways, here is the extension method (I only include cases for double and string, but in reality I have quite a few more):

public static T GetValue<T>(this JToken jToken, string key,
                            T defaultValue = default(T))
{
    T returnValue = defaultValue;

    if (jToken[key] != null)
    {
        object data = null;
        string sData = jToken[key].ToString();

        Type type = typeof(T);

        if (type is double)
            data = double.Parse(sData);
        else if (type is string)
            data = sData;

        if (null == data && type.IsValueType)
            throw new ArgumentException("Cannot parse type "" + 
                type.FullName + "" from value "" + sData + """);

        returnValue = (T)Convert.ChangeType(data, 
            type, CultureInfo.InvariantCulture);
    }

    return returnValue;
}

And here's an example of using the extension method:

width = jToken.GetValue<double>("width", 100);

BTW, Please forgive what may be a really dumb question, since it seems like something there should be a built in function for... I did try Google, and Json.NET documentation, however I'm either inept at finding the solution to my question or it's not clear in the documentation.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

This is pretty much what the generic method Value() is for. You get exactly the behavior you want if you combine it with nullable value types and the ?? operator:

width = jToken.Value<double?>("width") ?? 100;

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...