简体   繁体   English

如何检索元素键值?

[英]how to retrieve element key value?

I came across a problem, I need help to retrieve a certain key value when I scan the QR code, but for some reason I am retrieving the ID instead.我遇到了一个问题,我在扫描 QR 码时需要帮助来检索某个键值,但由于某种原因,我正在检索ID However, I want to get the CandidateID instead.但是,我想改为获取CandidateID Can anyone help me solve this issue?谁能帮我解决这个问题? thanks in advance.提前致谢。

JSON: JSON:

   {
    "ef4b0f54-e246-468b-ada9-465777c6e743": {    
        "CandiateID": "d9c4ba35-6c68-41de-b11c-f4226701c05a", // I want to retrieve  this when I scan the QR code. 
         "ID": "ef4b0f54-e246-468b-ada9-465777c6e743" // I am getting only this when I scan the QR Code.     
    }
} 

You are not getting the ID - You are reading the root value for the JSON.您没有获得ID - 您正在读取 JSON 的根值。 The values are aexactly the same so it only looks like you are reading the ID field.这些值完全相同,因此看起来您只是在读取 ID 字段。

When converting JSON to a dynamic object you can use the property indexers to access the correct value.将 JSON 转换为动态对象时,您可以使用属性索引器访问正确的值。

In your case you can use the following:在您的情况下,您可以使用以下内容:

var results = JsonConvert.DeserializeObject<dynamic>(barCodeValue);

string id = results["ef4b0f54-e246-468b-ada9-465777c6e743"]["CandiateID"];

The first value is the root element of the JSON.第一个值是 JSON 的根元素。

The second value is the field name within the JSON - CandiateID第二个值是 JSON 中的字段名称 - CandiateID

The local variable id now contains the CandiateID property from the JSON.局部变量id现在包含来自 JSON 的CandiateID属性。

You could use Linq for the purpose.您可以为此目的使用 Linq。 For example例如

var jObject = JObject.Parse(barCodeValue);
var candidateID = jObject.Descendants()
                         .OfType<JProperty>()
                         .Where(x=>x.Name=="CandiateID")
                         .First().Value;

If there are more than one CandidateID to be fetched, you could use如果要获取多个 CandidateID,您可以使用

var candidateIDs = jObject.Descendants()
                          .OfType<JProperty>()
                          .Where(x=>x.Name=="CandiateID")
                          .Select(x=>x.Value);

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

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