Converting newtonsoft code to System.Text.Json in .net core 3. what's equivalent of JObject.Parse and JsonProperty
You are asking a few questions here:
I am not able to find any equivalent for
JObject.Parse(json);
You can use
JsonDocument
to parse and examine any JSON, starting with itsRootElement
. The root element is of typeJsonElement
which represents any JSON value (primitive or not) and corresponds to Newtonsoft'sJToken
.But do take note of this documentation 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.
When you need to use a
JsonElement
outside the lifetime of its document, you must clone it:Gets a
JsonElement
that can be safely stored beyond the lifetime of the originalJsonDocument
.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.An example of use is as follows:
//https://learn.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);Also what will be the attribute
JsonProperty
equivalent?Attributes that can control
JsonSerializer
are placed in theSystem.Text.Json.Serialization
namespace and inherit from an abstract base classJsonAttribute
. UnlikeJsonProperty
, there is no omnibus attribute that can control all aspects of property serialization. Instead there are specific attributes to control specific aspects.As of .NET Core 3 these include:
[JsonPropertyNameAttribute(string)]
:Specifies the property name that is present in the JSON when serializing and deserializing. This overrides any naming policy specified by
JsonNamingPolicy
.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)]
: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.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]
- corresponds to Newtonsoft's[JsonExtensionData]
.[JsonIgnoreAttribute]
- corresponds to Newtonsoft's[JsonIgnore]
.
When writing JSON via
Utf8JsonWriter
, indentation can be controlled by settingJsonWriterOptions.Indented
totrue
orfalse
.When serializing to JSON via
JsonSerializer.Serialize
, indentation can be controlled by settingJsonSerializerOptions.WriteIndented
totrue
orfalse
.
Demo fiddle here showing serialization with JsonSerializer
and parsing with JsonDocument
.
equivalent of default value during Converting my newtonsoft implementation to new JSON library in .net core 3.0
As noted in Issue #38878: System.Text.Json option to ignore default values in serialization & deserialization, as of .Net Core 3 there is no equivalent to the DefaultValueHandling
functionality in System.Text.Json
.
.NET 5 and later introduce JsonIgnoreAttribute.Condition
, which has the following values:
public enum JsonIgnoreCondition
{
/// Property is never ignored during serialization or deserialization.
Never = 0,
/// Property is always ignored during serialization and deserialization.
Always = 1,
/// If the value is the default, the property is ignored during serialization.
/// This is applied to both reference and value-type properties and fields.
WhenWritingDefault = 2,
/// If the value is <see langword="null"/>, the property is ignored during serialization.
/// This is applied only to reference-type properties and fields.
WhenWritingNull = 3,
}
While JsonIgnoreCondition
superficially resembles DefaultValueHandling
, System.Text.Json ignores custom default values applied via DefaultValueAttribute
. Instead the default value used is always default(T)
. E.g. the following combination of attributes:
[DefaultValue(true)]
[JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingDefault)]
[JsonPropertyName("send_service_notification")]
public bool SendServiceNotification { get; set; }
Will result in SendServiceNotification
being skipped when false
not true
. In addition, System.Text.Json will not automatically populate the default value onto your model if not present in the JSON.
That being said, you are using DefaultValueHandling.Populate
:
Members with a default value but no JSON will be set to their default value when deserializing.
If your properties are mutable, this can be achieved by setting the default value in the constructor or property initializer:
//[DefaultValue(true)] not needed by System.Text.Json
[System.Text.Json.Serialization.JsonPropertyName("send_service_notification")]
public bool SendServiceNotification { get; set; } = true;
Demo fiddle here.
If you are using immutable properties that are set only via a parameterized constructor, in .NET 6 (and possibly .NET 5, I haven't checked) you can specify a default value in the constructor argument list and it will be honored by System.Text.Json when not present in the JSON. E.g. if you have a record:
public record SendServiceRecord (bool SendServiceNotification = true);
And you deserialize the JSON {}
, then SendServiceNotification
will be true after deserialization.
See demo fiddles here and here.
In fact the documentation for DefaultValueAttribute
recommends code initialization of default values:
A
DefaultValueAttribute
will not cause a member to be automatically initialized with the attribute's value. You must set the initial value in your code.
Related Topics
Win32_Processor::Is Processorid Unique for All Computers
Uploading Objects to Google Cloud Storage Buckets in C#
How to Convert C# Nullable Int to Int
How Does Transactionscope Roll Back Transactions
How to Convert PDF Files to Images
How to Ignore Null Values for All Source Members During Mapping in Automapper 6
Obtain Sha-256 String of a String
Getting Individual Windows Application Current Volume Output Level as Visualized in Audio Mixer
Does Stream.Dispose Always Call Stream.Close (And Stream.Flush)
Event Bubbling and Mvp: ASP.NET
How to Run and Interact with an Async Task from a Wpf Gui
Performance of Static Methods VS Instance Methods
Implementing Collectionchanged
Entity Framework/Sql2008 - How to Automatically Update Lastmodified Fields for Entities