首页 > 其他分享 >dotnet6使用System.Text.Json替代Newtonsoft.Json

dotnet6使用System.Text.Json替代Newtonsoft.Json

时间:2022-10-28 12:55:18浏览次数:88  
标签:00 Newtonsoft Text 08 JSON Json 2019 JsonNode

How to serialize and deserialize JSON using C# - .NET | Microsoft Learn

 

//序列化和反序列号范例
using System.Text.Json;

using System.Text.Encodings.Web;
using System.Text.Unicode;

namespace SerializeBasic
{
    public class WeatherForecast
    {
       //序列号时,把Date改为DateNow
       [JsonPropertyName("DateNow")]
        public DateTimeOffset Date { get; set; }
        public int TemperatureCelsius { get; set; }
        //JsonIgnore 序列化时忽略此属性
     [JsonIgnore]
        public string? Summary { get; set; }
        public string? Msg{get;set;}
    }

    public class Program
    {
        public static void Main()
        {
            var weatherForecast = new WeatherForecast
            {
                Date = DateTime.Parse("2022-08-01"),
                TemperatureCelsius = 25,
                Summary = "Hot",
          Msg="我是汉字"
            };
var options = new JsonSerializerOptions { 
WriteIndented = true,//缩进格式展示(方便阅读)
Encoder = JavaScriptEncoder.Create(UnicodeRanges.All)//支持汉字(所有unicode编码)
 };
            string jsonString = JsonSerializer.Serialize(weatherForecast,options);

            Console.WriteLine(jsonString);
// 序列化输出 output:
//{
//"DateNow":"2022-08-01T00:00:00-07:00",
//"TemperatureCelsius":25,
//"Msg":"我是汉字"
//}    
//反序列化 string jsonString = @"{ ""Date"": ""2019-08-01T00:00:00-07:00"", ""TemperatureCelsius"": 25, ""Summary"": ""Hot"", ""DatesAvailable"": [ ""2019-08-01T00:00:00-07:00"", ""2019-08-02T00:00:00-07:00"" ], ""TemperatureRanges"": { ""Cold"": { ""High"": 20, ""Low"": -10 }, ""Hot"": { ""High"": 60, ""Low"": 20 } }, ""SummaryWords"": [ ""Cool"", ""Windy"", ""Humid"" ] } "; WeatherForecast? weatherForecast = JsonSerializer.Deserialize<WeatherForecast>(jsonString); } } } 

 

使用 DOM 是使用 Json 序列化器反序列化的替代方法

例如没有要反序列化到的类型时。
或者收到的 JSON 没有固定的架构

How to use a JSON document, Utf8JsonReader, and Utf8JsonWriter in System.Text.Json | Microsoft Learn

使用此方法

sing System.Text.Json;
using System.Text.Json.Nodes;

namespace JsonNodeFromStringExample;

public class Program
{
    public static void Main()
    {
        string jsonString =
@"{
  ""Date"": ""2019-08-01T00:00:00"",
  ""Temperature"": 25,
  ""Summary"": ""Hot"",
  ""DatesAvailable"": [
    ""2019-08-01T00:00:00"",
    ""2019-08-02T00:00:00""
  ],
  ""TemperatureRanges"": {
      ""Cold"": {
          ""High"": 20,
          ""Low"": -10
      },
      ""Hot"": {
          ""High"": 60,
          ""Low"": 20
      }
  }
}
";
        // Create a JsonNode DOM from a JSON string.
        JsonNode forecastNode = JsonNode.Parse(jsonString)!;

        // Write JSON from a JsonNode
        var options = new JsonSerializerOptions { WriteIndented = true };
        Console.WriteLine(forecastNode!.ToJsonString(options));
        // output:
        //{
        //  "Date": "2019-08-01T00:00:00",
        //  "Temperature": 25,
        //  "Summary": "Hot",
        //  "DatesAvailable": [
        //    "2019-08-01T00:00:00",
        //    "2019-08-02T00:00:00"
        //  ],
        //  "TemperatureRanges": {
        //    "Cold": {
        //      "High": 20,
        //      "Low": -10
        //    },
        //    "Hot": {
        //      "High": 60,
        //      "Low": 20
        //    }
        //  }
        //}

        // Get value from a JsonNode.
        JsonNode temperatureNode = forecastNode!["Temperature"]!;
        Console.WriteLine($"Type={temperatureNode.GetType()}");
        Console.WriteLine($"JSON={temperatureNode.ToJsonString()}");
        //output:
        //Type = System.Text.Json.Nodes.JsonValue`1[System.Text.Json.JsonElement]
        //JSON = 25

        // Get a typed value from a JsonNode.
        int temperatureInt = (int)forecastNode!["Temperature"]!;
        Console.WriteLine($"Value={temperatureInt}");
        //output:
        //Value=25

        // Get a typed value from a JsonNode by using GetValue<T>.
        temperatureInt = forecastNode!["Temperature"]!.GetValue<int>();
        Console.WriteLine($"TemperatureInt={temperatureInt}");
        //output:
        //Value=25

        // Get a JSON object from a JsonNode.
        JsonNode temperatureRanges = forecastNode!["TemperatureRanges"]!;
        Console.WriteLine($"Type={temperatureRanges.GetType()}");
        Console.WriteLine($"JSON={temperatureRanges.ToJsonString()}");
        //output:
        //Type = System.Text.Json.Nodes.JsonObject
        //JSON = { "Cold":{ "High":20,"Low":-10},"Hot":{ "High":60,"Low":20} }

        // Get a JSON array from a JsonNode.
        JsonNode datesAvailable = forecastNode!["DatesAvailable"]!;
        Console.WriteLine($"Type={datesAvailable.GetType()}");
        Console.WriteLine($"JSON={datesAvailable.ToJsonString()}");
        //output:
        //datesAvailable Type = System.Text.Json.Nodes.JsonArray
        //datesAvailable JSON =["2019-08-01T00:00:00", "2019-08-02T00:00:00"]

        // Get an array element value from a JsonArray.
        JsonNode firstDateAvailable = datesAvailable[0]!;
        Console.WriteLine($"Type={firstDateAvailable.GetType()}");
        Console.WriteLine($"JSON={firstDateAvailable.ToJsonString()}");
        //output:
        //Type = System.Text.Json.Nodes.JsonValue`1[System.Text.Json.JsonElement]
        //JSON = "2019-08-01T00:00:00"

        // Get a typed value by chaining references.
        int coldHighTemperature = (int)forecastNode["TemperatureRanges"]!["Cold"]!["High"]!;
        Console.WriteLine($"TemperatureRanges.Cold.High={coldHighTemperature}");
        //output:
        //TemperatureRanges.Cold.High = 20

        // Parse a JSON array
        var datesNode = JsonNode.Parse(@"[""2019-08-01T00:00:00"",""2019-08-02T00:00:00""]");
        JsonNode firstDate = datesNode![0]!.GetValue<DateTime>();
        Console.WriteLine($"firstDate={ firstDate}");
        //output:
        //firstDate = "2019-08-01T00:00:00"
    }
}

 

标签:00,Newtonsoft,Text,08,JSON,Json,2019,JsonNode
From: https://www.cnblogs.com/imust2008/p/16835729.html

相关文章