C# 从 JToken 中获取可能不存在的价值(最佳实践)
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/9589218/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Get value from JToken that may not exist (best practices)
提问by Paul Hazen
What's the best practice for retrieving JSON values that may not even exist in C# using Json.NET?
使用Json.NET检索 C# 中甚至可能不存在的 JSON 值的最佳实践是什么?
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):
现在我正在处理一个 JSON 提供程序,它返回有时包含某些键/值对的 JSON,有时不包含。我一直在使用(可能是错误的)这种方法来获取我的值(获取双精度值的示例):
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 afterwriting 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.NETdocumentation, however I'm either inept at finding the solution to my question or it's not clear in the documentation.
顺便说一句,请原谅什么可能是一个非常愚蠢的问题,因为它看起来似乎应该有一个内置的函数...我曾尝试谷歌,Json.NET文档,但是我现在不是无能在寻找解决我的问题或文档中不清楚。
采纳答案by svick
回答by L.B
I would write GetValueas below
我会写GetValue如下
public static T GetValue<T>(this JToken jToken, string key, T defaultValue = default(T))
{
dynamic ret = jToken[key];
if (ret == null) return defaultValue;
if (ret is JObject) return JsonConvert.DeserializeObject<T>(ret.ToString());
return (T)ret;
}
This way you can get the value of not only the basic types but also complex objects. Here is a sample
通过这种方式,您不仅可以获得基本类型的值,还可以获得复杂对象的值。这是一个示例
public class ClassA
{
public int I;
public double D;
public ClassB ClassB;
}
public class ClassB
{
public int I;
public string S;
}
var jt = JToken.Parse("{ I:1, D:3.5, ClassB:{I:2, S:'test'} }");
int i1 = jt.GetValue<int>("I");
double d1 = jt.GetValue<double>("D");
ClassB b = jt.GetValue<ClassB>("ClassB");
回答by Dave Van den Eynde
You can simply typecast, and it will do the conversion for you, e.g.
您可以简单地进行类型转换,它会为您进行转换,例如
var with = (double?) jToken[key] ?? 100;
It will automatically return nullif said key is not present in the object, so there's no need to test for it.
null如果对象中不存在所述键,它将自动返回,因此无需对其进行测试。
回答by Artur Alexeev
Here is how you can check if the token exists:
以下是检查令牌是否存在的方法:
if (jobject["Result"].SelectToken("Items") != null) { ... }
It checks if "Items" exists in "Result".
它检查“结果”中是否存在“项目”。
This is a NOT working example that causes exception:
这是一个不工作的例子,导致异常:
if (jobject["Result"]["Items"] != null) { ... }
回答by Downhillski
TYPE variable = jsonbody["key"]?.Value<TYPE>() ?? DEFAULT_VALUE;
TYPE variable = jsonbody["key"]?.Value<TYPE>() ?? DEFAULT_VALUE;
e.g.
例如
bool attachMap = jsonbody["map"]?.Value<bool>() ?? false;
bool attachMap = jsonbody["map"]?.Value<bool>() ?? false;
回答by Max
This takes care of nulls
这会处理空值
var body = JObject.Parse("anyjsonString");
body?.SelectToken("path-string-prop")?.ToString();
body?.SelectToken("path-double-prop")?.ToObject<double>();

