I am getting a json object from an HTTP stream. I create a JObject using the following:
var stream = await client.GetStreamAsync(uri);
var root = JToken.Load(new JsonTextReader(new StreamReader(stream)));
This gives me the proper response. But now, I want to remove the last element of its results property which is an array (JArray). I use this code:
var results = (JArray)root["results"];
var last = results.Last(); // gets the last element -- correct
var removed = results.Remove(last); // removed = false and last not removed
var another = last.Remove(); // doesn't work either
I was able to remove a secret property from the root object itself using:
var removed = ((JObject)root).Remove("secret"); // removed = true, works
I can also add elements to the results array, but for some reason, I can’t remove them. What am I missing?
edit: after banging my head against the wall for a couple of hours and writing this post, I found out what was going on. The above code is a simplified version of my actual code. It is that simplification that is the answer actually. The original code was a bit more abbreviated:
var last = root["results"].ToObject<JArray>().Last();
last.Remove(); // did not work
The key is that I was mistakenly call ToObject<JArray>(). This broke the remove() logic most likely because the new object is not the same as the original JArray.
So, the posted code works as expected and I have updated my code be simpler too. Sorry for the noise here. A perfect illustration of Rubber Duck Problem Solving
re-posting here for clarity:
After banging my head against the wall for a couple of hours and writing this post, I found out what was going on. The above code is a simplified version of my actual code. It is that simplification that is the answer actually. The original code was a bit more abbreviated:
The key is that I was mistakenly calling
ToObject<JArray>(). This broke theremove()logic most likely because the new object is not the same as the originalJArray. So, the posted code works as expected and I have updated my code be simpler too. Sorry for the noise here. A perfect illustration of Rubber Duck Problem SolvingThanks to James N-K for both his quick response (on Twitter) and his great library. Thanked him by giving to his project, like Jeff Atwood taught us, more than once.