Mapping JSON Field Names to .NET Object Properties
Parsing JSON data into .NET objects often requires mapping JSON field names to corresponding object properties. This becomes crucial when JSON field names differ from .NET property names. While JavaScriptSerializer.Deserialize
might seem convenient, it doesn't always reliably handle name mismatches. A more robust solution utilizes DataContractJsonSerializer
.
Using DataContractJsonSerializer for Reliable Mapping
DataContractJsonSerializer
provides precise control over field name mapping through the DataMember
attribute. Here's how:
<code class="language-csharp">[DataContract] public class DataObject { [DataMember(Name = "user_id")] public int UserId { get; set; } [DataMember(Name = "detail_level")] public string DetailLevel { get; set; } }</code>
This code defines a DataObject
class. The DataMember
attribute explicitly maps the JSON fields "user_id" and "detail_level" to the .NET properties UserId
and DetailLevel
respectively.
Deserialization is then straightforward:
<code class="language-csharp">DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(DataObject)); MemoryStream ms = new MemoryStream(Encoding.Unicode.GetBytes(JsonData)); DataObject dataObject = serializer.ReadObject(ms) as DataObject;</code>
This code snippet deserializes the JSON data (JsonData
) into a DataObject
instance.
Considerations:
DataContractJsonSerializer
offers superior mapping capabilities compared to JavaScriptSerializer
, it might be slightly more verbose.DetailLevel
properties defined as enums, a custom DataContractResolver
can facilitate value mapping.DataContractJsonSerializer
is also compatible with Silverlight.The above is the detailed content of How to Map JSON Field Names to .NET Object Properties Using JavaScriptSerializer or DataContractJsonSerializer?. For more information, please follow other related articles on the PHP Chinese website!