简体   繁体   中英

JToken.ToString() removing curly braces

I have the following JToken :

{
    "ID": "9dbefe3f5424d972e040007f010038f2"
}

But whenever I run ToString() on the JToken object to get the underlying JSON in string form, it returns:

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

Escaping the quotes is expected, but why is it removing the curly braces? It's valid JSON. And this only seems to happen in certain cases, as I'm able to successfully run ToString() and have the curly braces intact on other (more complex) JTokens .

ToString() returns the JSON representation of the contents of the JToken . JToken is an abstract class, so what JSON is returned depends on what kind of JToken it is (as well as what it contains).

Here is a short example that should 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 are getting a bare name-value pair from ToString() you have a reference to a JProperty in your code, not a JObject . You should only expect to get complete (valid) JSON when you call ToString() on a JObject or a JArray .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM