I'm making a Web Service in C#
and I decided to use Newtonsoft.Json
to handle my Json
related tasks.
However, I'm having a problem for some time.
I made a minimal working example of the issue I'm currently having. I'm using .NET 7.0
.
I have the following class that I will return as a IActionResult
.
public record class Test
{
[JsonProperty]
public JArray Array { get; set; }
[JsonConstructor]
public Test() {
Array = new JArray();
}
}
This is what my code currently does:
[HttpGet("{test}")]
public IActionResult Test(string test)
{
Test a = new();
JObject b = new JObject();
b.Add("foo", "bar");
a.Array.Add(b);
return Ok(a);
}
And this is what I get in the Response Body:
{
"array": [
[
[
[]
]
]
]
}
What I expected to get was something like:
{
"array": [
{
"foo" : "bar"
}
]
}
I managed to narrow down the issue to either being in the JArray
or the JObject
, if I try to return the JObject
directly I get something like this:
{
"foo" : []
}
So I'm guessing It's failing to access the value of the property? What is weird about this is that if I do a JsonConvert.Serialize
and pass it either the JObject
or the Test
object, every value appears in the string, it's when I try to return the Objects that it fails to show the values.
I tried reading the Newtonsoft
documentation on the types JObject
and JArray
but I seem to be doing what is the required to get the correct result, I have the getters and setters, I have the Json
attributes, and there really isn't a whole lot of information on this particular issue I'm encountering.