问题描述
我正在将我的 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
.
推荐答案
你在这里问了几个问题:
You are asking a few questions here:
我找不到
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
在其文档的生命周期之外,您必须 克隆 它:
获取一个 JsonElement
,它可以在原始 JsonDocument
的生命周期之后安全存储.
Gets a
JsonElement
that can be safely stored beyond the lifetime of the originalJsonDocument
.
还要注意 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
等效?
可以控制的属性 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:
[JsonPropertyNameAttribute(字符串)]
:
指定在序列化和反序列化时出现在 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 anotherJsonConverterAttribute
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.Indented
为 true
或 false
.
通过 序列化为 JSON 时JsonSerializer.Serialize
,缩进可以通过设置JsonSerializerOptions.WriteIndented
为 true
或 false
.
Demo fiddle here 展示了使用 JsonSerializer
进行序列化并使用 JsonDocument<进行解析/代码>.
Demo fiddle here showing serialization with JsonSerializer
and parsing with JsonDocument
.
这篇关于在 .net core 3 中将 newtonsoft 代码转换为 System.Text.Json.相当于 JObject.Parse 和 JsonProperty的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!