0

I am downloading a JSON in the following format (which I can not change):

[
    {"Id":183,"description":"blahblahblah"},
    {"Id":184,"description":"blehblehbleh"},
    {"Id":1000,"description":"and so on..."}
]

How can I convert it to became a Dictionary<string, string> like so:

{
{"blahblahblah", "183"},
{"blehblehbleh", "184"},
{"and so on...", "1000"}
}

?

I´m using C# .Net Standard 2.0 (maybe I can use .Net 4.x)

1

2 Answers 2

2

I suggest, first convert your json to c# model using json2csharp

The model for your json looks like

public class KeyValue
{
    public int Id { get; set; }
    public string description { get; set; }
}

then use Newtonsoft.Json.JsonConvert.DeserializeObject to convert the json to object

var results = Newtonsoft.Json.JsonConvert.DeserializeObject<List<KeyValue>>(jsonString);

finally use foreach to move it to dictionary

Dictionary<int, string> keyValuePairs = new Dictionary<int, string>();
foreach (var keyvalue in results)
{
     keyValuePairs.Add(keyvalue.description, keyvalue.Id);
}
Sign up to request clarification or add additional context in comments.

Comments

1

You could use Newtonsoft.Json to deserialize your JSON into a dictionary.

Firstly, make an Item class(or whatever other name of class you choose).

public class Item
{
    [JsonProperty("Id")]
    public int Id { get; set; }

    [JsonProperty("description")]
    public string Description { get; set; }
}

Secondly, deserialize your json using JsonConvert.DeserializeObject()and assign the key as Description and the value as Id using Enumerable.ToDictionary(). Additionally, since your data is a JSON array, you should deserialize to a IEnumerable<Item> to get the correct results.

var json = "[{ \"Id\":183,\"description\":\"blahblahblah\"},{ \"Id\":184,\"description\":\"blehblehbleh\"},{ \"Id\":1000,\"description\":\"and so on...\"}]";

var deserializedJsonDict = JsonConvert
    .DeserializeObject<IEnumerable<Item>>(json)
    .ToDictionary(entry => entry.Description, entry => entry.Id);

foreach (var entry in deserializedJsonDict)
{
    Console.WriteLine($"Key={entry.Key}, Value={entry.Value}");
}

Output keys and values of dictionary:

Key=blahblahblah, Value=183
Key=blehblehbleh, Value=184
Key=and so on..., Value=1000

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.