Click here to Skip to main content
15,887,214 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi friends I am trying to convert json data to my Class in a generic list but I am getting this error
Cannot convert type 'System.Collections.Generic.Dictionary<string,object>' to 'string'

Please guide me I am confused where I am lacking or how can i get this data.

string result1 = "aab234cf34d
{ 
	"data": 
		[ 
			{ 
				"id": "xxxxxxxxxxxxxxxxxxx", 
				"first_name": "aaaaaa", 
				"last_name": "bbbbb", 
				"email": [ "eeeeeee","ffffff" ]
			}, 
			{ 
				"id": "yyyyyyyyyyyyyyyyyy", 
				"first_name": "cccccccccc", 
				"last_name": "ddddddd", 
				"email": [ "hhhhhhhh","ggggggg" ]
			}
		]
}";

class MyClass
    {
        public string id { get; set; }
        public string first_name { get; set; }
        public string last_name { get; set; }
        public string[] email { get; set; }     
    }
var jss = new System.Web.Script.Serialization.JavaScriptSerializer();
 dynamic dataJss = jss.Deserialize<dynamic>(result1);
                        
 List<MyClass> myList = new List<MyClass>();
 foreach (string key in dataJss["data"])
 {
       MyClass l =Newtonsoft.Json.JsonConvert.DeserializeObject<MyClass>(key);
       myList.Add(l);
 }
Posted

1 solution

Either use Newtonsoft.Json or Microsoft's JavaScriptSerializer, not both.

What you do now with the line jss.Deserialize<dynamic>(result1) you create an IDictionary<string,object>, where each object is again an IDictionary<string,object>.

To use Newtonsoft.Json, do something like this:
C#
JObject json = JObject.Parse(result1);
foreach (JObject o in json["data"])
{
    MyClass mc = new MyClass
                    {
                        id = o["id"].Value<string>(),
                        first_name = o["first_name "].Value<string>(),
                        last_name = o["last_name "].Value<string>(),
                        email = o["email"].Values<string>().ToArray() // ToArray is from Linq, Values<T>() will return an IEnumerable<T>, and ToArray() will make an array out of it.
                    };
    // etc...
}
 
Share this answer
 
v4

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900