Home > Backend Development > C++ > How to Map JSON Field Names to .NET Object Properties using JavaScriptSerializer (or Alternatives)?

How to Map JSON Field Names to .NET Object Properties using JavaScriptSerializer (or Alternatives)?

Linda Hamilton
Release: 2025-01-10 06:50:46
Original
116 people have browsed it

How to Map JSON Field Names to .NET Object Properties using JavaScriptSerializer (or Alternatives)?

Use JavaScriptSerializer.Deserialize: Map JSON field names to .NET object properties

Question:

How to map field names in JSON data to field names of a .NET object when using JavaScriptSerializer.Deserialize?

Answer:

The JavaScriptSerializer class does not provide direct field name mapping functionality. However, you can leverage the more flexible DataContractJsonSerializer class for this purpose.

To map field names:

  1. Add the DataContract attribute to your data object class:
<code>[DataContract]
public class DataObject
{
}</code>
Copy after login
  1. Use the DataMember attribute to specify the JSON property name corresponding to the object field:
<code>[DataMember(Name = "user_id")]
public int UserId { get; set; }

[DataMember(Name = "detail_level")]
public string DetailLevel { get; set; }</code>
Copy after login

Example:

<code>using System.Runtime.Serialization.Json;

public class Test
{
    public static void Main()
    {
        string json = "{\"user_id\":1234, \"detail_level\":\"low\"}";

        DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(DataObject));

        using (MemoryStream ms = new MemoryStream(Encoding.Unicode.GetBytes(json)))
        {
            DataObject dataObject = serializer.ReadObject(ms) as DataObject;

            Console.WriteLine(dataObject.UserId); // 输出:1234
            Console.WriteLine(dataObject.DetailLevel); // 输出:low
        }
    }
}</code>
Copy after login

Note:

  • If you want to keep the DetailLevel field as an enumeration, you can use a custom JSON converter to handle conversion between string and enumeration values.
  • DataContractJsonSerializer also supports field name mapping in Silverlight.

The above is the detailed content of How to Map JSON Field Names to .NET Object Properties using JavaScriptSerializer (or Alternatives)?. 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