-1

I have a JSON string which looks like:

[{"Id":"1","Name":"Apple "},{"Id":"2","Name":"Orange "},{"Id":"3","Name":"Banana "}....]

How can I convert the JSON string to this format: {"1":"Apple"},{"2":"Orange"},{"3","Banana"}... so I can create dictionary like:

Dictionary<string, string> d = new Dictionary<string, string>()
    {
        {"1":"Apple"},{"2":"Orange"},{"3","Banana"}
    };
Sam
  • 7,252
  • 16
  • 46
  • 65
user3399326
  • 863
  • 4
  • 13
  • 24

1 Answers1

1

You don't need to actually transform your original string to another format.

With the use of an intermediary class, as shown below, you can convert directly:

using Newtonsoft.Json;
using System.Linq;

Dictionary<string, string> tt = JsonConvert.DeserializeObject<List<DataObject>>(@"[{""Id"":""1"",""Name"":""Apple ""},{""Id"":""2"",""Name"":""Orange ""},{""Id"":""3"",""Name"":""Banana ""}]").ToDictionary(k => k.Id, v => v.Name);

public class DataObject
{
    public string Id { get; set; }
    public string Name { get; set; }
}

So what this does is first convert the Json array into a List<DataObject>, and then using the Linq ToDictionary operator we complete the job.

Hope this helps

Luc Morin
  • 5,302
  • 20
  • 39