简体   繁体   English

将C#中json上变量的值与字符串进行比较

[英]Comparing the value of a variable on json in C# to a string

I'm using a google API to get distance between two places and to check if I got distance information there's a status field on the json response for the API that can read "OK" or "NOT_AVAILABLE" or something along those lines. 我正在使用Google API来获取两个地方之间的距离,并检查是否获取了距离信息,该API的json响应上有一个状态字段,可以读取“ OK”或“ NOT_AVAILABLE”或类似的内容。 I want to check if the status is OK so I can use the distance info so I do it like this 我想检查状态是否正常,以便可以使用距离信息,所以我这样做

if (disJSON["rows"][0]["elements"][0]["status"] == "OK")

The thing is that it returns false everytime even if the status is OK 问题是即使状态为OK,它也会每次返回false

I looked into the debugger to check the value and the value the debugger shows for the above element of the json is "\\"OK\\"". 我调查了调试器以检查该值,调试器显示的json上面元素的值为“ \\” OK \\“”。 Which is weird. 这很奇怪。 So I used that as the comparison string on the if statement like this 所以我用它作为if语句的比较字符串,像这样

if (disJSON["rows"][0]["elements"][0]["status"] == "\"OK\"")

But it also returns false all the time. 但是它也总是返回false。 Any ideas how to compare this properly? 有什么想法如何正确比较吗?

I suspect the problem is that the compile-time type of disJSON["rows"][0]["elements"][0]["status"] is JToken or something like that. 我怀疑问题是disJSON["rows"][0]["elements"][0]["status"]的编译时类型是JToken或类似的东西。 If you cast to string, then a) you'll be comparing a string with a string; 如果转换为字符串,则a)将字符串与字符串进行比较; b) the compiler will use the bool ==(string, string) overload instead of comparing for reference identity: b)编译器将使用bool ==(string, string)重载,而不是比较引用标识:

string status = (string) disJSON["rows"][0]["elements"][0]["status"];
if (status == "OK")
{
    ...
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM