Home >Backend Development >C++ >How Can I Map Differently Named JSON Fields to C# Properties During Deserialization?
Change field name using JavaScriptSerializer.Deserialize
in C#
class in C# provides a convenient way to deserialize JSON data into C# objects. However, by default it maps JSON field names directly to property names in the target object. This can cause deserialization to fail when the JSON field name is inconsistent with the property name in the C# object. JavaScriptSerializer
1. Use the attribute XmlElement
attribute. However, as mentioned in the original post, this method does not work with [XmlElement]
. Field name mapping should be implemented using the JavaScriptSerializer
attribute instead. [DataMember]
2. Use DataContractJsonSerializer
The
System.Runtime.Serialization
namespace provide a more powerful solution for field name mapping. The corresponding JSON field name can be specified explicitly by applying the DataContractJsonSerializer
attribute on a C# object's property. [DataMember]
<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>In this example, the
and user_id
JSON field names map to detail_level
and UserId
properties in the C# object, respectively. DetailLevel
to deserialize JSON data: DataContractJsonSerializer
<code class="language-csharp">using System.Runtime.Serialization.Json; using System.Text; using System.IO; ... DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(DataObject)); MemoryStream ms = new MemoryStream(Encoding.Unicode.GetBytes(JsonData)); DataObject dataObject = serializer.ReadObject(ms) as DataObject;</code>By using the
and DataContractJsonSerializer
attributes, you can effectively change field names during JSON deserialization, ensuring correct mapping between JSON data and C# objects. [DataMember]
The above is the detailed content of How Can I Map Differently Named JSON Fields to C# Properties During Deserialization?. For more information, please follow other related articles on the PHP Chinese website!