JToken.ToString () removing curly braces

I have the following JToken

:

{
    "ID": "9dbefe3f5424d972e040007f010038f2"
}

      

But whenever I run ToString()

on an object JToken

to get the underlying JSON in string form, it returns:

\"ID\": \"9dbefe3f5424d972e040007f010038f2\"

      

Waiting for quotes is expected, but why does it remove the curly braces? This is valid JSON. And this only happens in some cases, since I can successfully run ToString()

and save the curly braces on a different (more complex) one JTokens

.

+3


source to share


1 answer


ToString()

returns a JSON representation of the content JToken

. JToken

is an abstract class, so the JSON returned depends on what it is JToken

(as well as what it contains).

Here's a quick example to illustrate the point:

class Program
{
    static void Main(string[] args)
    {
        JObject jo = new JObject();
        jo.Add("ID", "9dbefe3f5424d972e040007f010038f2");

        // token is a JObject
        DumpToken(jo);

        // token is a JProperty (the first property of the JObject)
        DumpToken(jo.Properties().First());

        // token is a JValue (the value of the "ID" property in the JObject)
        DumpToken(jo["ID"]);  
    }

    private static void DumpToken(JToken token)
    {
        Console.WriteLine(token.GetType().Name);
        Console.WriteLine(token.ToString());
        Console.WriteLine();
    }
}

      



Output:

JObject
{
  "ID": "9dbefe3f5424d972e040007f010038f2"
}

JProperty
"ID": "9dbefe3f5424d972e040007f010038f2"

JValue
9dbefe3f5424d972e040007f010038f2

      

So, I suspect that when you get a paired pair with a name ToString()

, you have a reference to JProperty

in your code, not to JObject

. You should only expect to receive the complete (valid) JSON when you call ToString()

on JObject

or JArray

.

+9


source







All Articles