C
C#10mo ago
Anarchist

Deserialise part of a json response

Hello, how could I use newtonsoft to deserialise part of a large json response into a smaller set of objects? e.g. if the response is...
{
"count": 100,
"next": "https://api",
"previous": null,
"results": [
{
"name": "a",
"id": 1,
"extra": "whatever"
},
{
"name": "b",
"id": 2,
"extra": "whatever"
},
]
}
{
"count": 100,
"next": "https://api",
"previous": null,
"results": [
{
"name": "a",
"id": 1,
"extra": "whatever"
},
{
"name": "b",
"id": 2,
"extra": "whatever"
},
]
}
...how would I extract just an array of the elements in result, with only some params, e.g. [ { "a", 1 }, { "b" , 2 } ]
9 Replies
Anarchist
AnarchistOP10mo ago
At the moment I keep getting null
Keswiik
Keswiik10mo ago
There are a couple different ways that come to mind: - (kinda ugly imo) Deserialize as a JObject, then access the key you want ("results"), re-serialize, and then deserialize to the desired type. - Create a new model to deserialize to that ONLY contains the properties you want to reference. Might need to update the deserializer config to ignore unknown properties. Obvious drawback is that you have extra overhead creating those models to handle it. - Deserialize to a Dictionary<string, string> which should give you a list of your top-level keys and the raw json they contain. You could then do a second deserialization of your desired type. In your case, it looks to be a List<SomeModelClass>. (note that I didn't test suggestion 3, so it might not work that way, but that's something you can do yourself)
Anarchist
AnarchistOP10mo ago
Thanks, I've got it working with "root" and "product" classes, where Root has a List<Product> Response and Product the desired attributes. A little bloated, but it seems to work.
Keswiik
Keswiik10mo ago
:PepoSalute:
Mayor McCheese
Mayor McCheese10mo ago
You can likely finagle something with jsonpath, but it's likely not worth the effort. Also iirc stj doesn't support jsonpath
Unknown User
Unknown User10mo ago
Message Not Public
Sign In & Join Server To View
jcotton42
jcotton4210mo ago
Correct
Mayor McCheese
Mayor McCheese10mo ago
Honestly just create a dto with needed properties only and call it a day.
Unknown User
Unknown User10mo ago
Message Not Public
Sign In & Join Server To View
Want results from more Discord servers?
Add your server