C
C#11mo ago
Pannekoekje

✅ How to deal with different JSON types

I have an API endpoint and depending on the query it can return a list of objects or an object as such: Query for multiple
{"option": "1", "response":[{"A": "A"}, {"B": "B"}]}
{"option": "1", "response":[{"A": "A"}, {"B": "B"}]}
Query for single
{"option": "1", "response":{"A": "A"}}
{"option": "1", "response":{"A": "A"}}
For now I'm only allowing queries for multiple but would like to support both.
public class Response
{
public string A { get; set; }
public string B { get; set; }
}

public class Root
{
public string option { get; set; }
public List<Response> response { get; set; }
}
public class Response
{
public string A { get; set; }
public string B { get; set; }
}

public class Root
{
public string option { get; set; }
public List<Response> response { get; set; }
}
Is there a way to support this?
6 Replies
Angius
Angius11mo ago
Oof, malformed JSON is never fun to deal with... You'll need a custom converter: https://stackoverflow.com/a/59430729/6042255
Pannekoekje
PannekoekjeOP11mo ago
I'm using polymorphic deserialization as well 😦 Already tried a custom converter, wont work in combination with it I found this
Pannekoekje
PannekoekjeOP11mo ago
GitHub
Combining 'JsonDerivedType' attribute with a custom 'JsonConverter'...
Issue summary The polymorphic JSON deserialization in System.Text.Json has some limitations when combined with custom JSON converters. This is documented here: Polymorphism using type discriminator...
Pannekoekje
PannekoekjeOP11mo ago
Oh I see in the thread you linked you can use it on specific properties, I'll try that out Woo, that works 🙂 thx
Denis
Denis11mo ago
$close
MODiX
MODiX11mo ago
Use the /close command to mark a forum thread as answered
Want results from more Discord servers?
Add your server