Explanation of various application class examples of Json string in C

  • 2021-08-17 00:53:15
  • OfStack

In the program, everything and information can be described and carried by objects. In addition to the popular xml, there is also a simple and fast form to deal with target information, that is, Json format.

First of all, Json format has its own fixed format: for example, person object can be simply expressed as {"name": "xxxx", "age": 12, "sex": "male"}.

The description of Json format is as follows: first, use {} to contain the object information to be expressed, use PropertyName: Value to describe the object attributes in {}, and Json strings can be nested in multiple layers. For example: Json data: [{PropertyName: Value, PropertyName: Value}, {PropertyName: Value, PropertyName: Value}], Json nesting format: {PropertyName: Value, PropertyName: {PropertyName: Value, PropertyName}}, theoretically infinitely nested, but it is recommended that no more than 3 layers be nested.

With an understanding of the Json format, how can we use Json in C # and associate implemented objects with Json? Give a few namespaces first

using Newtonsoft.Json;
using System.Runtime.Serialization;
using System.ServiceModel;
using Newtonsoft.Json.Linq;
using System.IO;
using System.Runtime.Serialization.Json;

Note here that these namespaces are supported in this release. net 3.5 and above, and you must add references to System. Runtime. Serialization. dll to the references.

The main classes used here are as follows:

JsonSerializer, StringWriter, StringReader, JsonWriter, JsonConvert, DataContractJsonSerializer.

1. Realize the mutual transformation between custom classes and Json:


 public class Person
  {
    public  Person()
    {
    }
    public Person(string Name, string Sex, int Age, string Address, PersonCharacter Character)
    {
      this.Name = Name;
      this.Sex = Sex;
      this.Age = Age;
      this.Address = Address;
      this.Character = Character;
    }
    public string Name { get; set; }
    public string Sex { get; set; }
    public int Age { get; set; }
    public string Address { get; set; }
    public PersonCharacter Character { get; set; }
  }
  public class PersonCharacter
  {
    public string Daode { get; set; }
    public string Wenhua { get; set; }
    public string Xiuyang { get; set; }
  }
 public void ShowConvert()
    {
      Person person = new Person("lanar", " Male ", 24, " Shaanxi ", new PersonCharacter());
      JsonSerializer serializer = new JsonSerializer();
StringWriter sw = new StringWriter();
serializer.Serialize(new JsonTextWriter(sw), person );
Console.WriteLine(sw.GetStringBuilder().ToString());
StringReader sr = new StringReader(@"{""Name"":""ppp"", ""Age"":"12"}");
Person p1 = (Project)serializer.Deserialize(new JsonTextReader(sr), typeof(Person));
Console.WriteLine(p1.Name+ "=>" + p1.Age);
}

2. Contract mode: Use DataContractJsonSerializer or JsonReaderWriterFactory implementation provided by System. Runtime. Serialization. dll


 public class Person
   {
     public  Person()
     {
     }
     public Person(string Name, string Sex, int Age, string Address, PersonCharacter Character)
     {
       this.Name = Name;
       this.Sex = Sex;
       this.Age = Age;
       this.Address = Address;
       this.Character = Character;
     }
     [DataMember]
     public string Name { get; set; }
     [DataMember]
     public string Sex { get; set; }
     [DataMember]
     public int Age { get; set; }
      [DataMember]
     public string Address { get; set; }
     [DataMember]
     public PersonCharacter Character { get; set; }
   }
   public class PersonCharacter
   {
     public string Daode { get; set; }
     public string Wenhua { get; set; }
     public string Xiuyang { get; set; }
   }
     public void ShowConvert()
     {
       Person person = new Person(" Xu Zhanpeng ", " Male ", , " Shaanxi ", new PersonCharacter());
       Person p = new Person() { Name = "4 Great Holy Land ", Age = , Sex = " Male ", Character = new PersonCharacter() { Daode="sds", Wenhua="dasd", Xiuyang="zzz"} };
       DataContractJsonSerializer serializer = new DataContractJsonSerializer(p.GetType());
       string jsonText;
       try
       {
         using (MemoryStream stream = new MemoryStream())
         {
           serializer.WriteObject(stream, p);
           jsonText = Encoding.UTF.GetString(stream.ToArray());
           Console.WriteLine(jsonText);
         }
         using (MemoryStream ms = new MemoryStream(Encoding.UTF.GetBytes(jsonText)))
         {
           DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(Person));
           Person p = (Person)serializer.ReadObject(ms);
         }
       }
       catch (Exception ex )
       {
         throw new Exception(ex.Message,ex);
       }
     }

To use the contract method, you must add related contract modifiers to the class and related attributes: [DataContract], [DataMember] can be embedded in the object without adding contract modifiers.

The above is just the most commonly used application mode, and the implementation with special requirements can be handled by using the json transformation class implemented by the third party. On the web page, you can use the JavaScriptSerializer class for simple serialization by introducing the System. Web. Script. Serialization namespace.


Related articles: