c# example - json serialization and json tree

Serialization

Due to the existence of pointer and reference types, in a running program, the data is not necessarily a whole block.
It may be scattered in various places in the memory.

Sequence refers to a continuous and orderly whole. Serialization is the process of turning data into a continuous and ordered whole.
The data processed in this way can be conveniently transmitted and stored.

Json serialization

json format

JSON is a text data format. The name of the data and the content of the data are represented in the form of key-value pairs.
In c#, time, numbers, strings and other basic types have built-in ways to convert directly with strings.
The complex type will disassemble its members through reflection until there are only basic types.

class Weapon
{
    
    
	public (int, int) Attack {
    
     get; set; }
	public float Speed {
    
     get; set; }
	public int Level {
    
     get; set; }
}
{
    
    
  "Attack": {
    
    
    "Item1": 10,
    "Item2": 20
  },
  "Speed": 1.5,
  "Level": 3
}

serialization api

Newtonsoft.JsonIt is a json serialization extension package commonly used in c#. Usually he will be referenced together with the template project creation.
If not, import the following namespace and right-click the installation Newtonsoft.Jsonpackage, VS will automatically find the corresponding extension package and download and reference it.

using Newtonsoft.Json;

Through JsonConvert.SerializeObjectthe method, any type can be serialized into a json string.
But by default only properties will be serialized, not fields.

Weapon weapon = new Weapon() {
    
     Attack = (10, 20), Speed = 1.5f, Level = 3 };
string json = JsonConvert.SerializeObject(weapon);
Console.WriteLine(json);

Use JsonConvert.DeserializeObjectthe method to deserialize a string into a type instance.
You need to use generics to accurately determine your target type.

string dejson = @"{""Attack"":{""Item1"":10,""Item2"":20},""Speed"":1.5,""Level"":3}";
Weapon deweapon = JsonConvert.DeserializeObject<Weapon>(dejson);
Console.WriteLine(deweapon.Attack);

Deserialization is assigned through reflection.

  • So if there is an attribute in the json content that your type does not have, this attribute will be ignored.
  • If the attribute required by your type does not exist in the content of json, then this attribute will not be assigned, and will only maintain the default value.
  • If your property doesn't have a set accessor, it won't be assigned.
  • If you have a parameter with the same name in your constructor, the parameter will be passed to the constructor, and the property will not be assigned a value afterwards.

Attributes Control Serialization Rules

Features can be identified during reflection. But different libraries may recognize different features.

public class Person
{
    
    
    // 指定json属性的名称为"name"
    [JsonProperty("name")]
    public string Name {
    
     get; set; }

    // 指定json属性的顺序为1
    [JsonProperty(Order = 1)]
    public int Age {
    
     get; set; }

    // 指定json属性为null时忽略不写入json中
    [JsonProperty(NullValueHandling = NullValueHandling.Ignore)]
    public string Gender {
    
     get; set; }
}

See other documentation for detailed feature controls. Serialization Attributes

JSON tree

In order to read json data, an entity class is usually made and then deserialized. Then get the data through the class instance.

{
    
    
  "Name": "Alice",
  "Age": 25,
  "Hobbies": [
    "Reading",
    "Cooking",
    "Gaming"
  ]
}

insert image description here
But if you don't want to do this, you can also read the data by parsing it into a Json type.

Json node type

  • JToken: the base class for all json nodes
    • Jobject: json object, surrounded by braces, contains multiple key-value pairs.
      • JProperty: Each pair of key-value pairs. Contains the name of the attribute and the value of the attribute.
        • JValue: The value of the attribute. Including Jobject, Jarray, or basic data types such as bool, int, string
    • Jarray: The array of json, the content surrounded by square brackets. There are a bunch of juxtaposed values ​​inside, and they don't have names.

parsing json

ParseStrings can be parsed from static methods of types such as Jobject, JArray, JToken, etc.
Or you can FromObjectserialize an instance.
The parsed JToken can be ToString as a serialized string, or ToObjectdeserialized into an instance.

string json = @"{
  ""Name"": ""Alice"",
  ""Age"": 25,
  ""Hobbies"": [
    ""Reading"",
    ""Cooking"",
    ""Gaming""
  ]
}";

var jobject = JObject.Parse(json);
var person = jobject.ToObject<Person>();
jobject = JObject.FromObject(person);
Console.WriteLine(jobject);

public class Person
{
    
    
	public string Name {
    
     get; set; }
	public int Age {
    
     get; set; }
	public string[] Hobbies {
    
     get; set; }
}

Get and modify node content

Jobject can obtain the content of child nodes through the indexer.
If it is a string, a JProperty of the same name in the child node is looked for.
If it is an int, then the content of the index will be looked up in the Jarray.

string json = @"{
  ""Name"": ""Alice"",
  ""Age"": 25,
  ""Hobbies"": [
    ""Reading"",
    ""Cooking"",
    ""Gaming""
  ]
}";

var jobject = JObject.Parse(json);
var jarr = jobject["Hobbies"];
Console.WriteLine(jarr);
Console.WriteLine(jarr[0]);

Nodes can be modified through indexers. But adding content to the array must be through the method of adding nodes.

jobject["Hobbies"][0] = "666";
jobject["Hobbies"][2].AddAfterSelf("14.6");
jobject["Date"] = "2012-4-8";
Console.WriteLine(jobject);

For basic types, they can be directly serialized by casting.
A cast to a reference type or a nullable value type returns null if there is no corresponding key-value pair.
If it is a value type and there is no corresponding key-value pair, or if the value cannot be resolved to the target type, then there will be an exception.

jobject["Date"] = "2012-4-8";  
DateTime date = (DateTime)jobject["Date"];
int? age = (int?)jobject["Age"];
string name = (string)jobject["Name"];
Console.WriteLine(date);
Console.WriteLine(age);
Console.WriteLine(name);

Guess you like

Origin blog.csdn.net/zms9110750/article/details/131703287