skip to Main Content

I have a data packet in following JSON format.

[{"C74": "123"}, {"C75": "32"}, {"C76": "11"}, {"C78": "15"}]

Is it possible to parse in following C# model?

{
   string key { get; set; }
   string value { get; set; }
}

2

Answers


  1. your string is not a Dictionary it’s a Dictionary[]

    So you have to deserialize it that way and convert it into your desired format.

    string input = "[{"C74": "123"}, {"C75": "32"}, {"C76": "11"}, {"C78": "15"}]";
    Dictionary<string, string>[] temp = Newtonsoft.Json.JsonConvert.DeserializeObject<Dictionary<string, string>[]>(input);
    Dictionary<string, string> result = temp.Select(x => x.First()).ToDictionary(x => x.Key, x => x.Value);
    
    Login or Signup to reply.
  2. Yes, you can parse it to a List, for example

    List<Item> items = JArray.Parse(json)
                             .SelectMany(ja => ((JObject)ja).Properties()
                             .Select(x => new Item { key = x.Name, 
                                                     value = (string)x.Value })
                             ).ToList();
    
    public class Item
    {
        public string key { get; set; }
        public string value { get; set; }
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search