Runtime: Converting newtonsoft code to System.Text.Json. what's equivalent of JObject.Parse

Created on 7 Oct 2019  路  3Comments  路  Source: dotnet/runtime

I am converting my newtonsooft implementeation to new javascript library in .net core 3.0
I have one of 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; }
}
area-System.Text.Json question

Most helpful comment

System.Text.Josn.JsonSerializer is a static class which has method Deserialize you can use.

var jsonString = "{\"status\": \"Good to go!\"}";
var myClass = System.Text.Json.JsonSerializer.Deserialize<MyClass>(jsonString);

For the PropertyName attribute you can use JsonPropertyName.

public class MyClass
{
    [JsonPropertyName("status")]
    public string Status { get; set; }
}

All 3 comments

System.Text.Josn.JsonSerializer is a static class which has method Deserialize you can use.

var jsonString = "{\"status\": \"Good to go!\"}";
var myClass = System.Text.Json.JsonSerializer.Deserialize<MyClass>(jsonString);

For the PropertyName attribute you can use JsonPropertyName.

public class MyClass
{
    [JsonPropertyName("status")]
    public string Status { get; set; }
}

Try JsonDocument.Parse:

```c#
static bool IsValidJson(string json)
{
try
{
System.Text.Json.JsonDocument.Parse(json);
return true;
}
catch (System.Exception ex) when
(ex is System.Text.Json.JsonException || ex is System.ArgumentException)
{
Logger.ErrorFormat("Invalid Json Received {0}", json);
Logger.Fatal(ex.Message);
}

return false;

}
```

Was this page helpful?
0 / 5 - 0 ratings