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:
<code>[DataContract] public class DataObject { }</code>
<code>[DataMember(Name = "user_id")] public int UserId { get; set; } [DataMember(Name = "detail_level")] public string DetailLevel { get; set; }</code>
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>
Note:
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!