将 newtonsoft 代码转换为 System.Text.Json in .net core 3. 相当于 JObject.Parse 和 JsonProperty [英] Converting newtonsoft code to System.Text.Json in .net core 3. what's equivalent of JObject.Parse and JsonProperty

查看:24
本文介绍了将 newtonsoft 代码转换为 System.Text.Json in .net core 3. 相当于 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 等效

Also what will be the attribute JsonProperty equivalent

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.

推荐答案

你在这里问几个问题:

  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.

但请注意此文档 备注:

这个类利用池内存中的资源来最小化垃圾收集器 (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 在其文档的生命周期之外,您必须克隆:

获取一个可以在原始 JsonDocument 生命周期之外安全存储的 JsonElement.

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

另请注意,JsonDocument 当前是 只读 并且不提供用于创建或修改 JSON 的 API.有一个未解决的问题 问题 #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(类型)]:

    当放置在类型上时,将使用指定的转换器,除非在 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.

    [JsonExtensionDataAttribute] - 对应于 Newtonsoft 的 [JsonExtensionData].

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

    通过 编写 JSON 时Utf8JsonWriter,可以通过设置JsonWriterOptions.Indentedtruefalse.

    当通过 序列化为 JSON 时JsonSerializer.Serialize,可以通过设置JsonSerializerOptions.WriteIndentedtruefalse.

    Demo fiddle 此处 显示使用 JsonSerializer 进行序列化并使用 JsonDocument<进行解析/代码>.

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

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

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