将对象序列化为 JavaScript 对象表示法 (JSON),并将 JSON 数据反序列化为对象。 此类不能继承。

//  msdn 例子:

namespace SL_DataContractJsonSerializer
{
    
public partial class Page : UserControl
    {
        
public Page()
        {
            InitializeComponent();
        }

        
//This uses an event handler, not SL data binding
        void OnClick(object sender, EventArgs args)
        {
            txtOutput1.Text 
= "Create a User object and serialize it.";
            
string json = WriteFromObject();
            txtOutput2.Text 
= json.ToString(); // Displays: {"Age":42,"Name":"Bob"}

            txtOutput3.Text 
= "Deserialize the data to a User object.";
            
string jsonString = "{'Name':'Bill', 'Age':53}";
            User deserializedUser 
= ReadToObject(jsonString);
            txtOutput4.Text 
= deserializedUser.Name; // Displays: Bill
            txtOutput5.Text = deserializedUser.Age.ToString(); // Displays: 53
        }
        
// Create a User object and serialize it to a JSON stream.
        public static string WriteFromObject()
        {
            
//Create User object.
            User user = new User("Bob"42);

            
//Create a stream to serialize the object to.
            MemoryStream ms = new MemoryStream();

            
// Serializer the User object to the stream.
            DataContractJsonSerializer ser = new DataContractJsonSerializer(typeof(User));
            ser.WriteObject(ms, user);
            
byte[] json = ms.ToArray();
            ms.Close();
            
return Encoding.UTF8.GetString(json, 0, json.Length);

        }

        
// Deserialize a JSON stream to a User object.
        public static User ReadToObject(string json)
        {
            User deserializedUser 
= new User();
            MemoryStream ms 
= new MemoryStream(Encoding.UTF8.GetBytes(json));
            DataContractJsonSerializer ser 
= new DataContractJsonSerializer(deserializedUser.GetType());
            deserializedUser 
= ser.ReadObject(ms) as User;
            ms.Close();
            
return deserializedUser;
        }

    }

    [DataContract]
    
public class User
    {
        [DataMember]
        
public string Name { getset; }

        [DataMember]
        
public int Age { getset; }

        
public User() { }

        
public User(string newName, int newAge)
        {
            Name 
= newName;
            Age 
= newAge;
        }

    }

}

相关文章:

  • 2022-12-23
  • 2021-10-16
  • 2021-10-16
  • 2022-02-13
  • 2022-01-21
  • 2021-12-26
  • 2021-09-26
猜你喜欢
  • 2021-09-12
  • 2021-06-01
  • 2022-12-23
  • 2022-02-10
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
相关资源
相似解决方案