C
C#

CatAPI Json deserialization issue.

CatAPI Json deserialization issue.

DDecabytes11/19/2023
I'm having trouble getting my code to deserialize my json correctly. When I run my Program.cs I get
API Response: [{"id":"530","url":"https://cdn2.thecatapi.com/images/530.jpg","width":448,"height":538}]
Deserialized Cat URL:
value=HereKitty.RandomCat
url=
API Response: [{"id":"530","url":"https://cdn2.thecatapi.com/images/530.jpg","width":448,"height":538}]
Deserialized Cat URL:
value=HereKitty.RandomCat
url=
But I'm not able to access the fields in the json. My Program.cs
var filePath = "/home/deca/auth/cat_api.json";
using var doc = JsonDocument.Parse(File.ReadAllText(filePath));
var apiKey = doc.RootElement.GetProperty("api_key").GetString();
var kitty = new HereKitty(apiKey);

var response = await kitty.GetRandomCatAsync();
Console.WriteLine($"value={response}");
Console.WriteLine($"url={response.Url}");
var filePath = "/home/deca/auth/cat_api.json";
using var doc = JsonDocument.Parse(File.ReadAllText(filePath));
var apiKey = doc.RootElement.GetProperty("api_key").GetString();
var kitty = new HereKitty(apiKey);

var response = await kitty.GetRandomCatAsync();
Console.WriteLine($"value={response}");
Console.WriteLine($"url={response.Url}");
my Json class
public class RandomCat
{
public string Id { get; set; }
public string Url { get; set; }
public int Width { get; set; }
public int Height { get; set; }
}
public class RandomCat
{
public string Id { get; set; }
public string Url { get; set; }
public int Width { get; set; }
public int Height { get; set; }
}
the response
{"id":"530","url":"https://cdn2.thecatapi.com/images/530.jpg","width":448,"height":538}
{"id":"530","url":"https://cdn2.thecatapi.com/images/530.jpg","width":448,"height":538}
my function
public async Task<RandomCat> GetRandomCatAsync()
{
var response = await _httpClient.GetAsync("images/search");
response.EnsureSuccessStatusCode();
var responseBody = await response.Content.ReadAsStringAsync();
Console.WriteLine($"API Response: {responseBody}");
using var jData = JsonDocument.Parse(responseBody);
var catData = jData.RootElement[0]; // Access the first element of the JSON array

RandomCat cat = JsonSerializer.Deserialize<RandomCat>(catData.GetRawText()); // Deserialize the first element
Console.WriteLine($"Deserialized Cat URL: {cat?.Url}");
return cat;
}
public async Task<RandomCat> GetRandomCatAsync()
{
var response = await _httpClient.GetAsync("images/search");
response.EnsureSuccessStatusCode();
var responseBody = await response.Content.ReadAsStringAsync();
Console.WriteLine($"API Response: {responseBody}");
using var jData = JsonDocument.Parse(responseBody);
var catData = jData.RootElement[0]; // Access the first element of the JSON array

RandomCat cat = JsonSerializer.Deserialize<RandomCat>(catData.GetRawText()); // Deserialize the first element
Console.WriteLine($"Deserialized Cat URL: {cat?.Url}");
return cat;
}
Does anyone know what I'm doing wrong?
AAngius11/19/2023
The [] means the response is an array, so could be that Also, why fiddle around with non-type-safe JsonDocument and what not instead of just... parsing the response to JSON?
DDecabytes11/20/2023
Ahh Thank you! GetFromJsonAsync works so much better! The other way I was doing it was
var response = await kitty.GetRandomCatAsync();
using var jData = JsonDocument.Parse(response);
var jDoc = jData.RootElement;
var catData = jDoc[0];
var url = catData.GetProperty("url").GetString();
var response = await kitty.GetRandomCatAsync();
using var jData = JsonDocument.Parse(response);
var jDoc = jData.RootElement;
var catData = jDoc[0];
var url = catData.GetProperty("url").GetString();
which was pain.
PPixxelKick11/20/2023
yeah its returning an array of RandomCat, not just 1
No description
PPixxelKick11/20/2023
it just happens to only be 1 item long So you wanna do JsonSerializer.Deserialize<RandomCat[]>
DIAdan in a can11/20/2023
glad it works!
MMMayor McCheese11/20/2023
Even just one cat has 9 lives

Looking for more? Join the community!

C
C#

CatAPI Json deserialization issue.

Join Server
Want results from more Discord servers?
Add your server
Recommended Posts
✅ Any idea why I cant use sendkey?Authorization in microservices archHello everyone, I'm quite new to the NET microservices arhitecture and right now I'm implementing a.✅ I can't get my runButton button to work on a windows form app```cs if (e.KeyCode == Keys.Enter || (e.Modifiers == Keys.None && sender == runButton)) ``` I can sGit and Google Drivenew git user.. it seems to have your local repositories in a google drive controlled file structure ASP.NET CRUD MODALI created a MVC controller with actions (CRUD) and I would like to know, how to modify this pre geneError✅ using from another csprojCurrently i have 2 projects, an api app and a worker service app And both use the same models. Is thJavascript not working on my MVC projectI'm learning front end tutorials at the moment so I'm totally new to designing websites. _Layout.csis there a way to get the colocation center connected to with C# ?I wanna get information about the colocation center exactly how Cloudflare warp gets it in the prefexaml and x:Class - issue (CS1061)I got a project wich some of you helped me with allready, tho there is still one issue I coudn't resCan't fire click blazor ui button```cs @page "/members" @namespace Blazor.Web @attribute [StreamRendering] <PageTitle>Members</PageTHelp Minecraft Console Client scripting(https://github.com/MCCTeam/Minecraft-Console-Client Link to MCC) is there a way to make a C# scrip✅ Bypass ASP.NET Required authenticatorIm trying to return Forbid (403) to the user if a resource already exists it all works fine but the Issues trying to create new error typesHello everyone. I'm trying to create my own extensible error type, based on the RFC 7807. ```c# puI have a Visual-Studio Proj. in .NET Framework and need help fixing the "CS0120" error it throws up.Basically I want to make an App which you just run and it will automatically, by pressing just one bplease help!!! (winforms c#)Does anyone know how can i make the user move the last drawn shape on a picturebox (the picture box WPF ScrollViewer issuesHello, I have the problem that the scrollviewer in C# (WPF) does not work properly. I haven't define✅ Quick - Unity "using" directiveReally quick question guys, when trying to use methods from other scripts in Unity, let's say the ot✅ .Split() Returning Spaces Between Words in String[]Hi. I have an string array `string[] strArr` of words in format `[word1, word2]` and so on - just a I want to compile a program myself with less filesI was working on a open source project, and I want to compile the program myself so I setup a github