Converting newtonsoft code to System.Text.Json in .net core 3. what's equivalent of JObject.Parse and JsonProperty

点点圈 提交于 2019-12-06 02:58:54

You are asking a few questions here:

  1. 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:

    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.

    Also note that this type is currently read-only and does not provide an API for creating or modifying JSON. There is currently an open issue Issue #39922: Writable Json DOM tracking this.

    An example of use is as follows:

    //https://docs.microsoft.com/en-us/dotnet/csharp/whats-new/csharp-8#using-declarations 
    using var doc = JsonDocument.Parse(json);
    
    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
    
    using var ms = new MemoryStream();
    using (var writer = new Utf8JsonWriter(ms, new JsonWriterOptions { Indented = true }))
    {
        doc.WriteTo(writer);
    }
    var json2 = Encoding.UTF8.GetString(ms.ToArray());
    
    Console.WriteLine(json2);
    
  2. Also what will be the attribute JsonProperty equivalent?

    Attributes that can control JsonSerializer are placed in the System.Text.Json.Serialization namespace. Unlike JsonProperty, 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 another JsonConverterAttribute on a property of the same 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].

  3. When writing JSON via Utf8JsonWriter, indentation can be controlled by setting JsonWriterOptions.Indented to true or false.

    When serializing to JSON via JsonSerializer.Serialize, indentation can be controlled by setting JsonSerializerOptions.WriteIndented to true or false.

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

This link should get you going, snippets of which I copied below.

https://devblogs.microsoft.com/dotnet/try-the-new-system-text-json-apis/


WeatherForecast Deserialize(string json)
{
    var options = new JsonSerializerOptions
    {
        AllowTrailingCommas = true
    };
    return JsonSerializer.Parse<WeatherForecast>(json, options);
}

class WeatherForecast {
    public DateTimeOffset Date { get; set; }

    // Always in Celsius.
    [JsonPropertyName("temp")]
    public int TemperatureC { get; set; }

    public string Summary { get; set; }

    // Don't serialize this property.
    [JsonIgnore]
    public bool IsHot => TemperatureC >= 30;
}

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!