This is a follow-up to my question here. I'm trying to understand how to serialize some JSON. I am using the JSON.stringify() method found in json2.js to convert a JSON array into a string value I can work with on the server-side. My JSON originally looks like this:
var myItems = {
"data": [
{"id":1, "type":2, "name":"book"},
{"id":2, "type":3, "name":"dvd"},
{"id":3, "type":4, "name":"cd"}
]
};
After I use JSON.stringify, I have noticed that the value on the server looks like the following:
{"data":[{"id":1,"type":2,"name":"book"},{"id":2,"type":"3","name":"dvd"},{"id":3,"type":4,"name":"cd"}]}
In an effort to serialize this JSON into C# objects I can work with, I have written the following code:
public MyItems GetMyItems()
{
MyItems items = new MyItems();
string json = serializedJsonInHiddenHtmlElement.Value;
if (json.Length > 0)
{
items = Deserialize<MyItems>(json);
}
return items;
}
public static T Deserialize<T>(string json)
{
using (MemoryStream ms = new MemoryStream(Encoding.UTF8.GetBytes(json)))
{
DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(T));
return (T)serializer.ReadObject(ms);
}
}
The classes associated with my types are defined as follows:
[DataContract(Name="myItems")]
internal class MyItems
{
[DataMember(Name = "data")]
public string[] Data { get; set; }
}
[DataContract(Name="myItem")]
internal class MyItem
{
[DataMember(Name = "id")]
public string ID { get; set; }
[DataMember(Name = "type")]
public string Type { get; set; }
[DataMember(Name = "name")]
public string Name { get; set; }
}
When I execute this code, the line that says return (T)serializer.ReadObject(ms); I get an error that says the following:
There was an error deserializing the object of type AppNamespace.MyItems. End element 'item' from namespace '' expected. Found element 'id' from namespace ''.
What am I doing wrong? I can't seem to get past this. Can somebody please point me in the right direction? Thank you!