I've been testing dynamically handling json on my backend without using objects (since I won't know the structure of the objects and it's a complete waste of my time creating them for the thousands of connections this will be making). I want to be able to program an interface without having to custom code every single rest interface I will be hooking up to and put the data in the hands of technical people but not programmers like myself.
In playing with NewtonSoft.Json I've come to realize that there are some oddities that I'm not quite understanding and I'm not alone as I've seen numerous people write similar questions with no resolution or understanding of what is going on.
I found numerous questions on here that referred to DeserializeObject as returning a JObject with an extra set of curly braces.
Example:
String "data" contains this:
{\r\n \"firstName\": \"John\",\r\n \"lastName\": \"Doe\",\r\n \"IDNum\": 123456,\r\n \"phoneNumbers\": [\r\n {\r\n \"number\": \"6123334444\"\r\n },\r\n {\r\n \"number\": \"7635556666\"\r\n }\r\n ]\r\n}
JObject rest = JsonConvert.DeserializeObject<dynamic>(data.ToString());
But the JObject "rest" gets an extra set of curly braces added to it:
{{
"firstName": "John",
"lastName": "Doe",
"IDNum": 123456,
"phoneNumbers": [
{
"number": "6123334444"
},
{
"number": "7635556666"
}
]
}}
Making this JArray command not functional:
JArray obj = JArray.Parse(rest ) as JArray;
One of the posts on here referred to converting it back to a string and just replacing the curly braces like this:
string cleanRest = rest.ToString().Replace("{{", "{").Replace("}}", "}");
Which ends up with this in string "cleanRest":
{\r\n \"firstName\": \"John\",\r\n \"lastName\": \"Doe\",\r\n \"IDNum\": 123456,\r\n \"phoneNumbers\": null\r\n}
Of course cleanRest is not a valid json and that line throws the error: "Newtonsoft.Json.JsonReaderException: 'Error reading JArray from JsonReader. Current JsonReader item is not an array: StartObject. Path '', line 1, position 1.'" when running the following line:
JArray obj = JArray.Parse(cleanRest) as JArray;
I first had issues with the response including xmlns: http://schemas.microsoft.com/2003/10/Serialization and I had to open it as an XmlDocument and convert it with this:
private string returnJson(string response)
{
XmlDocument doc = new XmlDocument();
doc.LoadXml(response);
return doc.DocumentElement.FirstChild.InnerText;
}
But all this noodling around is making me think I'm not dealing with this correctly even though I read a couple of blogs that referred to MS implementation of json has weird quirks like this. But I shouldn't have to mend the response; that's just making me nervous for future issues with this.
Does anyone know what is going on and how to solve it?