c# JSON serialization & deserialization

Introduction:

JSON (full name JavaScript ObjectNotation) is a lightweight data exchange format. It is based on a subset of the JavaScript syntax standard. JSON is a completely language-independent text format that can be easily transferred across various networks, platforms, and programs. The syntax of JSON is simple, easy for humans to read and write, and easy for machines to parse and generate.

Download the NuGet package

The first step to operate JSON in C# is to download the required NuGet package Newtonsoft.Json. It should be noted that in the same solution, different types of downloaded Nuget packages must be kept in the same version, otherwise an error may be reported.

deserialization

String string converted to class

first create a class

public class Site
{
    public int Id { get; set; }
    public string Name { get; set; }
}

Convert the string into an entity class, and then print it out through the entity class

    [Test]
    public void TestJsonToObject()
    {
        string json = "{\"Id\":1,\"Name\":\"爱吃香蕉的阿豪\"}";
        var site = JsonConvert.DeserializeObject<Site>(json) as Site;
        Console.WriteLine($"Id={site.Id}");
        Console.WriteLine("Nmae="+site.Name);
    }

json file into class

In actual work, when we have a lot of json content, it is impossible to write it in the class, so we need to write it in a json file, and then get it through the path

Create a data class

public class JsonData
{
    public List<Data> data { get; set; }
}

public class Data
{
    public int id { get; set; }
    public string name { get; set; }
}

Create a json file

{
  "data": [
    {
      "id" : 1,
      "name" : "爱吃香蕉的阿豪"
    },
    {
      "id" : 2,
      "name" : "张三"
    },
    {
      "id" : 3,
      "name" : "李四"
    }
  ]
}

test class

    [Test]
    public void TestJsonText()
    {
        var json = File.ReadAllText(@"D:\project\c#\Solution\Project\JSON\data.json");
        var JsonData = JsonConvert.DeserializeObject<JsonData>(json);
        foreach (var data in JsonData.data)
        {
            Console.WriteLine("id="+data.id + "   data="+data.name);
        }
    }

Serialization

Follow the deserialized Site class, first create a new class, set the value of the field, and then serialize it into a string and print it out

    [Test]
    public void TestObjectToJson()
    {
        Site site = new() { Id = 2, Name = "laowan" };
        var serializeObject = JsonConvert.SerializeObject(site);
        Console.WriteLine(serializeObject);
    }

Guess you like

Origin blog.csdn.net/weixin_65243968/article/details/129719604