Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 549
Soham Dasgupta Avatar asked Aug 14 '13 07:08

Soham Dasgupta


People also ask

Why does my JSON have backslash?

Those backslashes are escape characters. They are escaping the special characters inside of the string associated with JSON response. You have to use JSON. parse to parse that JSON string into a JSON object.

Can JSON be serialized?

JSON is a format that encodes an object to a string. On the transmission of data or storing is a file, data need to be in byte strings, but as complex objects are in JSON format. Serialization converts these objects into byte strings which is JSON serialization.

Does JSON serialize data?

The json module exposes two methods for serializing Python objects into JSON format. dump() will write Python data to a file-like object. We use this when we want to serialize our Python data to an external JSON file. dumps() will write Python data to a string in JSON format.


2 Answers

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.

like image 148
xanatos Avatar answered Oct 05 '22 23:10

xanatos


string str = "Your string with slashes";

str = JToken.Parse({your string here}).ToString();
like image 40
Damini Suthar Avatar answered Oct 05 '22 23:10

Damini Suthar