Json.NET adding backslash while returning json ser

2019-01-06 23:31发布

问题:

I am trying to serialize a list to json string using Json.NET but the return string has backslash within it, which in turn is failing a json parsing.

var x = from d in entities.Books.ToList()
        select new
        {
            ID = d.ID,
            BookName = d.BookName
        };
return JsonConvert.SerializeObject(x.ToList());

The above code returns

"[{\"ID\":1,\"BookName\":\"MVC Music Store - Tutorial - v3.0\"},{\"ID\":2,\"BookName\":\"Pro.ASP.NET.MVC.3.Framework\"},{\"ID\":3,\"BookName\":\"Application Architecture Guide v2\"},{\"ID\":4,\"BookName\":\"Gang of Four Design Patterns\"},{\"ID\":5,\"BookName\":\"CS4 Pocket Reference\"}]"

which fails all JSON parsing. How can I remove these.

回答1:

No. it doesn't

class Program
{
    class Book
    {
        public int ID;
        public string BookName;
    }

    static void Main()
    {
        var books = new List<Book> { new Book { ID = 1, BookName = "A" }, new Book { ID = 2, BookName = "B" } };

        var x = from d in books
        select new
        {
            ID = d.ID,
            BookName = d.BookName
        };

        string str = JsonConvert.SerializeObject(x.ToList());
        Console.WriteLine(str);
    }
}

There could be two problems:

A) You are looking at the result from the debugger. To check for this, Put the JsonConvert in a temporary variable (like I did) and look at it with the debugger. Click on the arrow right of the hourglass and select Text Visualizer.

or

B) The calling method is transforming the object again to Json, so escaping everything.



回答2:

string str = "Your string with slashes";

str = JToken.Parse({your string here}).ToString();


回答3:

The JSON object is serialized twice.

I solved by:

Declaring the operation contract of the method response format to return JSON. I changed the method to return an object instead of a string.

The serializing of Jason will be done automatically behind the scenes.