How to re-write the statement with System.Text.Json.

john zyd 421 Reputation points
2021-02-25T10:01:05.357+00:00

Hello: I had some C# code from former colleague using Newtonsoft.Json, I want to replace Newtonsoft.Json with built-in System.Text.Json, but I can’t reach my former colleague. I need some advice on how to re-write the statement with System.Text.Json. return JsonConvert.DeserializeObject<Icollection<SessionInfo>>(remoteSessions); The following is the code snippet: By the way, I am using Visual Studio 2019 (Version 16.8.6) on Windows 10 (Version 20H2) Thanks,

public class SessionInfo
{
[JsonProperty("description")]
public string Description
{
get;
set;
}

[JsonProperty("FrontendUrl")]
public string FrontendUrl
{
get;
set;
}

[JsonProperty("id")]
public string Id
{
get;
set;
}

[JsonProperty("title")]
public string Title
{
get;
set;
}

[JsonProperty("type")]
public string Type
{
get;
set;
}

[JsonProperty("DebuggerUrl")]
public string DebuggerUrl
{
get;
set;
}
}

public static async Task<ICollection<SessionInfo>> GetSessions(string Url)
{
using (var webClient = new HttpClient())
{
webClient.BaseAddress = new Uri(Url);
var remoteSessions = await webClient.GetStringAsync("/json");
return JsonConvert.DeserializeObject<ICollection<SessionInfo>>(remoteSessions);
}
}
Visual Studio Debugging
Visual Studio Debugging
Visual Studio: A family of Microsoft suites of integrated development tools for building applications for Windows, the web and mobile devices.Debugging: The act or process of detecting, locating, and correcting logical or syntactical errors in a program or malfunctions in hardware. In hardware contexts, the term troubleshoot is the term more frequently used, especially if the problem is major.
939 questions
0 comments No comments
{count} votes

Accepted answer
  1. Michael Taylor 48,046 Reputation points
    2021-02-25T15:43:51.61+00:00

    Did you already read the migration guide from MS on this?

    There are quite a few scenarios that won't work with the new parser so you have to code around them on a case by case basis. On a cursory glance it looks like your data type should be fine as is so the only change you need is the deserialization.

       //return JsonConvert.DeserializeObject<ICollection<SessionInfo>>(remoteSessions);  
       return JsonSerializer.Deserialize<ICollection<SessionInfo>>(remoteSessions);  
    

0 additional answers

Sort by: Most helpful