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...
...how would I extract just an array of the elements in result, with only some params, e.g.
[ { "a", 1 }, { "b" , 2 } ]
9 Replies
At the moment I keep getting null
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)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.:PepoSalute:
You can likely finagle something with jsonpath, but it's likely not worth the effort.
Also iirc stj doesn't support jsonpath
Unknown User•10mo ago
Message Not Public
Sign In & Join Server To View
Correct
Honestly just create a dto with needed properties only and call it a day.
Unknown User•10mo ago
Message Not Public
Sign In & Join Server To View