在.net core 3中将newtonsoft代码转换为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

查看:856
本文介绍了在.net core 3中将newtonsoft代码转换为System.Text.Json.等效于JObject.Parse和JsonProperty的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am converting my newtonsoft implementation to new JSON library in .net core 3.0. I have the following code

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.

One more thing i will be looking for the equivalent of Formating.None.

推荐答案

您在这里问了几个问题:

You are asking a few questions here:

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

您可以使用 JsonDocument 解析并检查任何JSON,以其 RootElement .根元素的类型为 JsonElement ,表示任何JSON值(是否为原始值),并对应于Newtonsoft的 JToken .

You can use 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.

但是请务必注意此文档备注:

But do take note of this documentation remark:

此类使用池内存中的资源来最大程度地减少高使用率场景中垃圾收集器(GC)的影响.无法正确处理该对象将导致内存没有返回到池中,这会增加GC对框架各个部分的影响.

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 在其文档生命周期之外,您必须

获取一个JsonElement,可以在原始JsonDocument的生命周期内对其进行安全存储.

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

还请注意,JsonDocument当前为问题#39922:可写Json DOM 对此进行跟踪.

Also note that JsonDocument is currently read-only and does not provide an API for creating or modifying JSON. There is an open issue Issue #39922: Writable Json DOM tracking this.

使用示例如下:

//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);

  • JsonProperty等效属性是什么?

  • Also what will be the attribute JsonProperty equivalent?

    可以控制 JsonSerializer 放在 System.Text.Json.Serialization 命名空间并从抽象基类继承 JsonAttribute .与JsonProperty不同,没有可以控制属性序列化所有方面的综合属性.而是有特定的属性来控制特定的方面.

    Attributes that can control JsonSerializer are placed in the System.Text.Json.Serialization namespace and inherit from an abstract base class JsonAttribute. Unlike JsonProperty, there is no omnibus attribute that can control all aspects of property serialization. Instead there are specific attributes to control specific aspects.

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

    As of .NET Core 3 these include:

    指定序列化和反序列化时JSON中存在的属性名称.这将覆盖 JsonNamingPolicy .

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

    这是您要用来控制ResponseJson类的序列化名称的属性:

    This is attribute you want to use to control the serialized names of your 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)] :

  • [JsonConverterAttribute(Type)]:

    放置在类型上时,将使用指定的转换器,除非将兼容的转换器添加到JsonSerializerOptions.Converters集合中,或者在相同类型的属性上存在另一个JsonConverterAttribute.

    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.

    请注意, Newtonsoft转换器,它是 JsonConverter定义的通过成员上的属性,然后是通过类上的属性定义的JsonConverter,最后是传递给JsonSerializer的所有转换器.

    Note that the 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, which is the JsonConverter defined by attribute on a member, then the JsonConverter defined by an attribute on a class, and finally any converters passed to the JsonSerializer.

    [JsonExtensionData] .

    [JsonIgnoreAttribute] -对应于Newtonsoft的 [JsonIgnore] .

    通过 ,可以通过设置 JsonWriterOptions.Indented truefalse.

    When writing JSON via Utf8JsonWriter, indentation can be controlled by setting JsonWriterOptions.Indented to true or false.

    通过 ,可以通过设置 JsonSerializerOptions.WriteIndented truefalse.

    When serializing to JSON via JsonSerializer.Serialize, indentation can be controlled by setting JsonSerializerOptions.WriteIndented to true or false.

    演示小提琴此处显示了JsonSerializer的序列化和JsonDocument的解析.

    Demo fiddle here showing serialization with JsonSerializer and parsing with JsonDocument.

    这篇关于在.net core 3中将newtonsoft代码转换为System.Text.Json.等效于JObject.Parse和JsonProperty的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

  • 查看全文
    登录 关闭
    扫码关注1秒登录
    发送“验证码”获取 | 15天全站免登陆