从值访问密钥

时间:2018-08-21 09:16:56

标签: c#

我想从值访问密钥。而且我能够从钥匙中获取价值。 我的json文件外观为

{
    "screen": {
        "0": "42x11",
        "1": "16x16",
        "2": "40x30",
        "3": "32x32",
        "4": "42x32",
        "5": "48x32",
        "6": "60x40",
        "7": "150x40",
        "8": "84x48"
    },
    "os": {
        "0": {
            "versions": {
                "1": {
                    "name": "10"
                },
                "2": {
                    "name": "8"
                },
                "3": {
                    "name": "7"
                }
            },
            "name": "Windows"
        }
    },
    "app": {
        "1": {
            "name": "javaScript1",
            "versions": {
                "1": {
                    "name": "1.0"
                }
            }
        }
    }

} 

我已经使用JavaScriptSerializer解析了文件。

public void deserialize_metadata()
{
   using (StreamReader r = new StreamReader("C:\\Users\\vikash.kumar\\Desktop\\metadatainfo.json"))
   {
        var json = r.ReadToEnd();
        var jss = new JavaScriptSerializer();
        var dict = jss.Deserialize<Dictionary<string, dynamic>>(json);
        Console.WriteLine("dict" + dict["screen"]["0"]);    //o/p - 42x11
        Console.WriteLine("dict" + dict["app"]["1"]["name"]); //o/p - javaScript1
      }
}

当我们想从键访问值时,它工作正常。

如何通过此过程从值中访问键?

1 个答案:

答案 0 :(得分:0)

duplicate中,尝试:dict["screen"].FirstOrDefault(x => x.Value == "42x11")?.Key

我添加了?.,以解决.FirstOrDefault在没有匹配项的情况下可以返回null的可能性。这样,它不会引发异常,而只会返回null

修改

Console.WriteLine((dict["screen"] as Dictionary<string, dynamic>)
                      .First(x => x.Value == "16x16").Key);