简体   繁体   English

如何从格式化为JSON字符串的字符串中获取值?

[英]How to get value from a string which is formatted as JSON string?

I have a string with a formatting like this: 我有一个格式如下的字符串:

[["addr","field"],["Administrator@cadomain.com",1000],["test1@cadomain.com",1001],["test2@cadomain.com",1002],["67656x3434",100],["99999",511],["79898",400],["545654",561],["7979",200],["6776767",201],["4656",300],["88888",5000]]

I want to get the addre (value) base on the field (key). 我想获得基于字段(键)的地址(值)。 I read some article about how to get value from a JSON string at: 我在以下位置阅读了一些有关如何从JSON字符串获取值的文章:

Read JSON string as key value 读取JSON字符串作为键值

How to read this json string using c#? 如何使用C#读取此json字符串?

But it does not work for me. 但这对我不起作用。

Any ideas, guys? 大家有什么想法吗?

If you use the Json.Net library to parse the JSON, you can get the data into a Dictionary<int, string> like this: 如果使用Json.Net库解析JSON,则可以将数据放入Dictionary<int, string>如下所示:

JToken token = JToken.Parse(json);

Dictionary<int, string> dict = 
    token.Skip(1).ToDictionary(a => (int)a[1], a => (string)a[0]);

Then you can use the dictionary like you normally would to access the data. 然后,您可以像平常一样使用字典来访问数据。

Demo: https://dotnetfiddle.net/Icyv1O 演示: https : //dotnetfiddle.net/Icyv1O


If you can only use .Net 2.0, you can do the same thing like this: 如果只能使用.Net 2.0,则可以执行以下操作:

JToken token = JToken.Parse(json);
Dictionary<int, string> dict = new Dictionary<int, string>();

bool skippedFirstItem = false;
foreach (JToken item in token)
{
    if (skippedFirstItem)
        dict.Add((int)item[1], (string)item[0]);
    else
        skippedFirstItem = true;
}

Demo: https://dotnetfiddle.net/zDvQFF 演示: https : //dotnetfiddle.net/zDvQFF

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

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