0

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:

Read JSON string as key value

How to read this json string using c#?

But it does not work for me.

Any ideas, guys?

Community
  • 1
  • 1
NoName
  • 877
  • 12
  • 28

1 Answers1

1

If you use the Json.Net library to parse the JSON, you can get the data into a Dictionary<int, string> like this:

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


If you can only use .Net 2.0, you can do the same thing like this:

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

Brian Rogers
  • 125,747
  • 31
  • 299
  • 300