0

I have a scnerio where i donot know the names of the keys so properties can;t be created beforehand. The JSON needs to be parsed and loaded into Dictionary that is present in a class. The format of JSON is like

 "SearchCriteria":{         
        "firstname":"user1",
        "surname":"User2"                       
    },
 "RequiredGroups":{         
        "UserGroup":"g1",
        "TeacherGroup":"g2"                     
    }

The problem is that the Parameters count and name are not known and can be anything. The JSON also contains other sections as well such as RequiredGroups which have known key names and are mapped with Objects. Need to convert into Dictionary. Any leads....

abdul
  • 157
  • 5
  • 18

2 Answers2

0

Example using Newtonsoft.Json.Linq:

using System;
using Newtonsoft.Json.Linq;
                    
public class Program
{
    public static void Main()
    {
        string json = @"{'SearchCriteria':{'firstname':'user1','surname':'User2'},'RequiredGroups':{'UserGroup':'g1','TeacherGroup':'g2'}}";
        JObject o = JObject.Parse(json);
        var dict = o.ToObject<Dictionary<string, object>>();
    }
}
bugcatcher9000
  • 201
  • 2
  • 5
0

string str1 = "{\"SearchCriteria\":{ \"firstname\":\"user1\", \"surname\":\"User2\" }, \"RequiredGroups\":{ \"UserGroup\":\"g1\",\"TeacherGroup\":\"g2\"  }}";

            var jObject1 = JObject.Parse(str1);
            Dictionary<string, string> dictObj = new Dictionary<string, string>();

            IList<string> keys = jObject1.Properties().Select(p => p.Name).ToList();
            foreach(var k in keys)
            {
                var s = jObject1[k].ToString();
                dictObj.Add(k, s);
            }
LDS
  • 354
  • 3
  • 9