Anonymous Anonymous - 9 days ago
112 0

No description

C#

Is it possible to deserialize nested dictionary?

class Program
	{
		static void Main(string[] args)
		{
			string json = @"
			{
				""name1"": 1,
				""name2"": {
					""name21"": ""2"",
					""name22"": 3
				},
				""name3"": [
					""text"",
					{
						""name311"": ""4"",
						""name312"": 5
					},
					{
						""name321"": 6,
						""name322"": ""7""
					}
				],
				""name4"":true,
				""name5"":""8""
			}
			";

			Console.WriteLine(json);

			var settings = new DataContractJsonSerializerSettings();
			settings.UseSimpleDictionaryFormat = true;
			Dictionary<string, object> dic = null;

			Console.WriteLine("Deserialize");
			using (MemoryStream ms = new MemoryStream(Encoding.UTF8.GetBytes(json)))
			{
				var ser = new DataContractJsonSerializer(typeof(Dictionary<string, object>), settings);
				dic = ser.ReadObject(ms) as Dictionary<string, object>;
			}

			Console.WriteLine("Serialize");
			using (MemoryStream ms = new MemoryStream())
			{
				var ser = new DataContractJsonSerializer(dic.GetType(), settings);
				ser.WriteObject(ms, dic);
				json = Encoding.UTF8.GetString(ms.ToArray());
			}

			Console.WriteLine(json);
		}
	}