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;
}
}
I am not able to find any equivalent for JObject.Parse(json);
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; }
}
One more thing i will be looking for the equivalent of Formating.None
.
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. But do take note of this documentation remark:When you need to use a
JsonElement
outside the lifetime of its document, you must clone it: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:
Also what will be the attribute
JsonProperty
equivalent?Attributes that can control
JsonSerializer
are placed in theSystem.Text.Json.Serialization
namespace. 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)]
:This is attribute you want to use to control the serialized names of your
ResponseJson
class:[JsonConverterAttribute(Type)]
:Note that the documented priority of converters -- settings before attributes -- is opposite 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 withJsonDocument
.This link should get you going, snippets of which I copied below.
https://devblogs.microsoft.com/dotnet/try-the-new-system-text-json-apis/