-1

I have this request

var response = await client.GetAsync("https://api.github.com/[path]");

and I should get this response

{
  "name": "",
  "path": "",
  "sha": "",
  "size": ,
  "url": "",
  "html_url": "",
  "git_url": "",
  "download_url": "",
  "type": "",
  "content": "",
  "encoding": "",
  "_links": {
    "self": "",
    "git": "",
    "html": ""
  }
}

And I want to parse this to get the "sha" value.

I tried everything I could find, so I can't rly show you what I have tried. I hope someone will be able to help me, ty.

Drag and Drop
  • 2,672
  • 3
  • 25
  • 37
  • Does this answer your question? [How can I parse JSON with C#?](https://stackoverflow.com/questions/6620165/how-can-i-parse-json-with-c) – Alejandro Sep 05 '20 at 16:51
  • Your `json` format is **incorrect** – Farhad Zamani Sep 05 '20 at 16:51
  • I know Farhad bcs when I try this dynamic stuff = JsonConvert.DeserializeObject(response); It tells me that I cannot convert it to string.... – Wilhelm Mertiny Sep 05 '20 at 16:55
  • Please show one example of what you have tried. There's a lot of info on parsing JSON on the web, I assume you found Newtonsoft (JSON.NET)? – CodeCaster Sep 05 '20 at 16:57
  • _"It tells me that I cannot convert it to string"_ - that is the compiler telling you you can't pass an HttpResponseMessage class (or something like that) to string, the latter of which JSON.NET expects. It hasn't even reached the point where it's running and actually trying to parse the JSON, where the only invalid thing is a missing number after "size", which you obviously cut. Please read [ask] and provide all relevant code and the verbatim (i.e. not interpreted by you) compiler error messages. – CodeCaster Sep 05 '20 at 16:58

1 Answers1

0

Create a class like this

public class Links    
{
    public string self { get; set; } 
    public string git { get; set; } 
    public string html { get; set; } 
}

public class Root    
{
    public string name { get; set; } 
    public string path { get; set; } 
    public string sha { get; set; } 
    public object size { get; set; } 
    public string url { get; set; } 
    public string html_url { get; set; } 
    public string git_url { get; set; } 
    public string download_url { get; set; } 
    public string type { get; set; } 
    public string content { get; set; } 
    public string encoding { get; set; } 
    public Links _links { get; set; } 
}

Install Newtonsoft.Json package on your project.

Read json from response.Content as string.

Deserialize json to Root object

var response = await client.GetAsync("https://api.github.com/[path]");
var json = await response.Content.ReadAsStringAsync();
var data = JsonConvert.DeserializeObject<Root>(json);
//data.sha
Farhad Zamani
  • 5,381
  • 2
  • 16
  • 41