C
C#4mo 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
Anarchist4mo ago
At the moment I keep getting null
Keswiik
Keswiik4mo 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
Anarchist4mo 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
Keswiik4mo ago
:PepoSalute:
Mayor McCheese
Mayor McCheese4mo 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 User4mo ago
Message Not Public
Sign In & Join Server To View
jcotton42
jcotton424mo ago
Correct
Mayor McCheese
Mayor McCheese4mo ago
Honestly just create a dto with needed properties only and call it a day.
Unknown User
Unknown User4mo ago
Message Not Public
Sign In & Join Server To View