0

I'm getting used to using System.Text.Json and I am wondering if there is a way to parse a JSON Response without knowing the fields that will come down. As an example the code I have to get an access token is as such:

HttpWebRequest request = (HttpWebRequest)WebRequest.Create(baseUrl + resource);
        request.Method = WebRequestMethods.Http.Post;            
        request.Headers["Authorization"] = "Basic "+credentials;
        HttpWebResponse response = (HttpWebResponse)request.GetResponse();
        Stream stream = response.GetResponseStream();
        StreamReader streamReader = new StreamReader(stream);
        var ddoc = JsonSerializer.Deserialize<JsonValues>(streamReader.ReadToEnd());
        bearerAuth = ddoc.Access_Token;

That's all well and good as the JsonValues class contains an Access_Token object. But is it possible to download and parse the JSON values without knowing the object names first and not have them in a class?

I'd still prefer to be able to access them through ddoc.XYZABC if possible?

Poul Bak
  • 10,450
  • 5
  • 32
  • 57
ConnorM
  • 9
  • 1
  • 7
  • 2
    You may use `JsonDocument` for that. However, your question is unclear, as well as the reason of using an obsolete `WebRequest` class instead of `HttpClient` – Pavel Anikhouski Oct 03 '20 at 17:28
  • Looks like a duplicate of [Converting newtonsoft code to System.Text.Json in .net core 3. what's equivalent of JObject.Parse and JsonProperty](https://stackoverflow.com/q/58271901/3744182), agree? Your case is specifically the equivalent of `JObject.Parse()`. You can't access freeform JSON values using dynamic properties though, `System.Text.Json` doesn't support that. See: [Read value from dynamic property from json payload](https://stackoverflow.com/a/64036531/3744182). Agree your question is a duplicate of those two? – dbc Oct 03 '20 at 18:10
  • 1
    _[Important](https://learn.microsoft.com/en-us/dotnet/api/system.net.httpwebrequest?view=netframework-4.8#remarks): We don't recommend that you use `HttpWebRequest` for new development. Instead, use the [`System.Net.Http.HttpClient`](https://learn.microsoft.com/en-us/dotnet/api/system.net.http.httpclient?view=netframework-4.8) class._ – aepot Oct 03 '20 at 18:16

0 Answers0