Summary: How do I map a field name in JSON data to a field name of a .Net object when using JavaScriptSerializer.Deserialize ?
Longer version: I have the following JSON data coming to me from a server API (Not coded in .Net)
{"user_id":1234, "detail_level":"low"}
I have the following C# object for it:
[Serializable]
public class DataObject
{
[XmlElement("user_id")]
public int UserId { get; set; }
[XmlElement("detail_level")]
public DetailLevel DetailLevel { get; set; }
}
Where DetailLevel is an enum with "Low" as one of the values.
This test fails:
[TestMethod]
public void DataObjectSimpleParseTest()
{
JavaScriptSerializer serializer = new JavaScriptSerializer();
DataObject dataObject = serializer.Deserialize<DataObject>(JsonData);
Assert.IsNotNull(dataObject);
Assert.AreEqual(DetailLevel.Low, dataObject.DetailLevel);
Assert.AreEqual(1234, dataObject.UserId);
}
And the last two asserts fail, since there is no data in those fields. If I change the JSON data to
{"userid":1234, "detaillevel":"low"}
Then it passes. But I can't change the server's behaviour, and I want the client classes to have well-named properties in the C# idiom. I can't use LINQ to JSON since I want it to work outside of Silverlight. It looks like the XmlElement tags are having no effect. I don't know where I got the idea they were relevant at all, they probably aren't.
How do you do field name mapping in JavaScriptSerializer? Can it be done at all?
Json.NET will do what you want. It supports reading DataContract/DataMember attributes as well as its own to change the property names. Also there is the StringEnumConverter class for serializing enum values as the name rather than the number.
Create a class inherited from JavaScriptConverter. You must then implement three things:
Methods-
Property-
You can use the JavaScriptConverter class when you need more control over the serialization and deserialization process.
Here is a link for further information