Migrate to Microsoft JSON

Emirates Angels 66 Reputation points
2020-12-29T08:58:51.617+00:00

Hi,

I want to migrate all my newtonsoft json's to Microsoft's JSON. Can you helo with below sample and how to migrate it please?

var client = new HttpClient();

client.BaseAddress = new Uri("https://www.mydomain.com/pin.php");

var content = new FormUrlEncodedContent(new[]
{
    new KeyValuePair<string, string>("email", TextEmail.Text.Trim()),
});

var response = await client.PostAsync("https://www.mydomain.com/pin.php", content);

var result = await response.Content.ReadAsStringAsync();

dynamic data = JsonConvert.DeserializeObject(result);

Thank you
Jassim

C#
C#
An object-oriented and type-safe programming language that has its roots in the C family of languages and includes support for component-oriented programming.
10,413 questions
0 comments No comments
{count} votes

Accepted answer
  1. Viorel 113.3K Reputation points
    2020-12-29T10:08:08.74+00:00

    Right-click the project in Solution Explorer, select “Manage NuGet packages…”, go to Browse tab, type “System.Text.Json” and install this package.

    Then try this code:

    using System.Dynamic;  
    using System.Text.Json;  
    . . .  
    string result = "{\"a\":\"hello\", \"b\":1}";  
      
    dynamic data = JsonSerializer.Deserialize<ExpandoObject>( result );  
      
    string a = data.a.GetString( );  
    int b = data.b.GetInt32( );  
    

    Using dynamic is not always reasonable. Usually, it is more convenient to define a class for required fields, such as:

    class MyData  
    {  
     public string a { get; set; }  
     public int b { get; set; }  
    }  
    

    Then you will write:

    MyData data = JsonSerializer.Deserialize<MyData>( result );  
      
    string a = data.a;  
    int b = data.b;  
    

    Adjust it according to further operations, which were not shown.

    See also DeserializeAsync and https://learn.microsoft.com/en-us/dotnet/standard/serialization/system-text-json-migrate-from-newtonsoft-how-to.

    0 comments No comments

2 additional answers

Sort by: Most helpful
  1. Emirates Angels 66 Reputation points
    2020-12-29T11:54:32.987+00:00

    How about the count of the data? is it possible using data.Count or the only way is to loop?


  2. Emirates Angels 66 Reputation points
    2020-12-29T16:31:21.75+00:00
    0 comments No comments