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.
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.
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.
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.
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.
string str = "Your string with slashes";
str = JToken.Parse({your string here}).ToString();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With