将 newtonsoft 代码转换为 .net core 3 中的 System.Text.Json。JObject.Parse 和 JsonProperty 的等效项

Converting newtonsoft code to System.Text.Json in .net core 3. what's equivalent of JObject.Parse and JsonProperty

我正在将我的 newtonsoft 实现转换为 .net core 3.0 中的新 JSON 库。我有以下代码

public static bool IsValidJson(string json)
{
    try
    {                
        JObject.Parse(json);
        return true;
    }
    catch (Exception ex)
    {
        Logger.ErrorFormat("Invalid Json Received {0}", json);
        Logger.Fatal(ex.Message);
        return false;
    }
}

我找不到 JObject.Parse(json);

的任何等价物

还有什么属性JsonProperty等价

public class ResponseJson
{
    [JsonProperty(PropertyName = "status")]
    public bool Status { get; set; }
    [JsonProperty(PropertyName = "message")]
    public string Message { get; set; }
    [JsonProperty(PropertyName = "Log_id")]
    public string LogId { get; set; }
    [JsonProperty(PropertyName = "Log_status")]
    public string LogStatus { get; set; }

    public string FailureReason { get; set; }
}

还有一件事我会寻找 Formating.None 的等价物。

这个 link 应该可以让你继续,我在下面复制了其中的片段。

https://devblogs.microsoft.com/dotnet/try-the-new-system-text-json-apis/

WeatherForecast Deserialize(string json) { var options = new JsonSerializerOptions { AllowTrailingCommas = true }; return JsonSerializer.Parse<WeatherForecast>(json, options); } class WeatherForecast { public DateTimeOffset Date { get; set; } // Always in Celsius. [JsonPropertyName("temp")] public int TemperatureC { get; set; } public string Summary { get; set; } // Don't serialize this property. [JsonIgnore] public bool IsHot => TemperatureC >= 30; }

你在这里问了几个问题:

  1. 我找不到 JObject.Parse(json);

    的任何等价物

    您可以使用 JsonDocument to parse and examine any JSON, starting with its RootElement. The root element is of type JsonElement which represents any JSON value (primitive or not) and corresponds to Newtonsoft's JToken

    但请注意此文档 remark:

    This class utilizes resources from pooled memory to minimize the impact of the garbage collector (GC) in high-usage scenarios. Failure to properly dispose this object will result in the memory not being returned to the pool, which will increase GC impact across various parts of the framework.

    当你需要使用一个JsonElement outside the lifetime of its document, you must clone它:

    Gets a JsonElement that can be safely stored beyond the lifetime of the original JsonDocument.

    另请注意,JsonDocument 目前正在 read-only and does not provide an API for creating or modifying JSON. There is an open issue Issue #39922: Writable Json DOM 跟踪此内容。

    使用示例如下:

    //https://docs.microsoft.com/en-us/dotnet/csharp/whats-new/csharp-8#using-declarations 
    using var doc = JsonDocument.Parse(json);
    
    //Print the property names.
    var names = doc.RootElement.EnumerateObject().Select(p => p.Name);
    Console.WriteLine("Property names: {0}", string.Join(",", names)); // Property names: status,message,Log_id,Log_status,FailureReason
    
    //Re-serialize with indentation.
    using var ms = new MemoryStream();
    using (var writer = new Utf8JsonWriter(ms, new JsonWriterOptions { Indented = true }))
    {
        doc.WriteTo(writer);
    }
    var json2 = Encoding.UTF8.GetString(ms.GetBuffer(), 0, checked((int)ms.Length));
    
    Console.WriteLine(json2);
    
  2. 还有什么属性 JsonProperty 等效?

    可以控制JsonSerializer are placed in the System.Text.Json.Serialization namespace and inherit from an abstract base class JsonAttribute的属性。与 JsonProperty 不同,没有可以控制 属性 序列化所有方面的综合属性。相反,有特定的属性来控制特定的方面。

    从 .NET Core 3 开始,这些包括:

    • [JsonPropertyNameAttribute(string)]:

      Specifies the property name that is present in the JSON when serializing and deserializing. This overrides any naming policy specified by JsonNamingPolicy.

      这是您要用来控制 ResponseJson class:

      的序列化名称的属性
      public class ResponseJson
      {
          [JsonPropertyName("status")]
          public bool Status { get; set; }
          [JsonPropertyName("message")]
          public string Message { get; set; }
          [JsonPropertyName("Log_id")]
          public string LogId { get; set; }
          [JsonPropertyName("Log_status")]
          public string LogStatus { get; set; }
      
          public string FailureReason { get; set; }
      }
      
    • [JsonConverterAttribute(Type)]:

      When placed on a type, the specified converter will be used unless a compatible converter is added to the JsonSerializerOptions.Converters collection or there is another JsonConverterAttribute on a property of the same type.

      请注意 documented priority of converters -- Attribute on property, then the Converters collection in options, then the Attribute on type -- differs from the documented order for Newtonsoft converters,即 成员上的属性定义的 JsonConverter,然后是 class 上的属性定义的 JsonConverter,最后传递的任何转换器到 JsonSerializer.

    • [JsonExtensionDataAttribute] - corresponds to Newtonsoft's [JsonExtensionData].

    • [JsonIgnoreAttribute] - corresponds to Newtonsoft's [JsonIgnore].

  3. 当通过 Utf8JsonWriter, indentation can be controlled by setting JsonWriterOptions.Indented 将 JSON 写入 truefalse.

    当通过 JsonSerializer.Serialize, indentation can be controlled by setting JsonSerializerOptions.WriteIndentedtruefalse 序列化到 JSON 时。

演示 fiddle here 显示使用 JsonSerializer 序列化并使用 JsonDocument 解析。