1

I have the following text that I need to put into a dictionary. At first sight I thought that it would be very easy but at the end I found myself doing extensive string search and finding sometimes values that break the parser.

"0": 
{
    "key":"valueWithAnyCharInside",
    "key2":"valueWithAnyCharInside",
    "key3":"valueWithAnyCharInside" 
},

This will map into the following model:

class Item
{
    private int id;
    private Dictionary<string, string> data;
}

Any ideas? Maybe using regex ...

melwil
  • 2,547
  • 1
  • 19
  • 34
Ignacio Soler Garcia
  • 21,122
  • 31
  • 128
  • 207

1 Answers1

4

Your data format is probably a JSON, but you gave only a part of it. I've modified it slightly as:

{"0":
    {
        "key":"valueWithAnyCharInside",
        "key2":"valueWithAnyCharInside",
        "key3":"valueWithAnyCharInside" 
    }
}

now you can parse it as following:

string json = ...; //your json goes here

var serializer = new JavaScriptSerializer();
var parsed =  serializer.Deserialize<Dictionary<string, Dictionary<string, string>>>(json);

//printing data
parsed["0"].Select(pair => string.Format( "{0} - {1}", pair.Key, pair.Value))
           .ToList()
           .ForEach(Console.WriteLine);

prints:

key - valueWithAnyCharInside
key2 - valueWithAnyCharInside
key3 - valueWithAnyCharInside

To get strongly typed List<Item> use next code

List<Item> items = parsed.Select(pair => new Item { Id = int.Parse(pair.Key),
                                                    Data = pair.Value})
                         .ToList();

Where Item is :

class Item
{
    public int Id { get; set; }
    public Dictionary<string, string> Data {get;set;}
}
Ilya Ivanov
  • 23,148
  • 4
  • 64
  • 90