Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
102 views
in Technique[技术] by (71.8m points)

c# - Json.NET adding backslash while returning json serialized string

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...