Home > Backend Development > C++ > How to Map JSON Field Names to .NET Object Properties Using JavaScriptSerializer or DataContractJsonSerializer?

How to Map JSON Field Names to .NET Object Properties Using JavaScriptSerializer or DataContractJsonSerializer?

Mary-Kate Olsen
Release: 2025-01-10 09:04:42
Original
608 people have browsed it

How to Map JSON Field Names to .NET Object Properties Using JavaScriptSerializer or DataContractJsonSerializer?

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>
Copy after login

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>
Copy after login

This code snippet deserializes the JSON data (JsonData) into a DataObject instance.

Considerations:

  • While DataContractJsonSerializer offers superior mapping capabilities compared to JavaScriptSerializer, it might be slightly more verbose.
  • For 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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template