C
C#2y ago
.tree

❔ Models for JSON from API

In Tim Coreys video he had an API with this sort of JSON structure: results: sunrise: "value" sunset: "value" For this he created two models, one for the actual keys called SunModel, and one for the results, which has a field of type SunModel called Results. Now I have this API that I want to call: times: 2023-10-29: 0: "value" 1: "value" So I have one more layer, what would be the best approach for this? To make one Model for times, one for 2023-10-29 and one for the actual keys 0 and 1? Also, since I can't name the variable in my model class 0, how do I tell my application to get this specific value? Can I index it?
6 Replies
Angius
Angius2y ago
2023-10-29 strikes me as a dictionary key So do the 0 and 1 ones Alternatively, that could also be an array
.tree
.treeOP2y ago
What do you mean by dictionary key?
Angius
Angius2y ago
Some Dictionary<DateOnly, string[]> comes to mind Or Dictionary<DateOnly, Dictionary<int, string>>
.tree
.treeOP2y ago
I don't quite follow, are you suggesting my model should be of that type?
MODiX
MODiX2y ago
Angius#1586
REPL Result: Success
using System;
using System.Collections.Generic;
using System.Text.Json;

var json = """
{
"times": {
"2023-10-29": {
"0": "value",
"1": "value"
}
}
}
""";

var data = JsonSerializer.Deserialize<Root>(json);

class Root {
public Dictionary<DateOnly, Dictionary<int, string>> times { get; set; }
}

data
using System;
using System.Collections.Generic;
using System.Text.Json;

var json = """
{
"times": {
"2023-10-29": {
"0": "value",
"1": "value"
}
}
}
""";

var data = JsonSerializer.Deserialize<Root>(json);

class Root {
public Dictionary<DateOnly, Dictionary<int, string>> times { get; set; }
}

data
Result: Root
{
"times": {
"2023-10-29": {
"0": "value",
"1": "value"
}
}
}
{
"times": {
"2023-10-29": {
"0": "value",
"1": "value"
}
}
}
Quoted by
<@!85903769203642368> from #bot-spam (click here)
Compile: 517.866ms | Execution: 57.476ms | React with ❌ to remove this embed.
Accord
Accord2y ago
Was this issue resolved? If so, run /close - otherwise I will mark this as stale and this post will be archived until there is new activity.
Want results from more Discord servers?
Add your server