Json.NET 在返回 json 序列化字符串时添加反斜杠 [英] Json.NET adding backslash while returning json serialized string
问题描述
我正在尝试使用 Json.NET 将列表序列化为 json 字符串,但返回字符串中包含反斜杠,这反过来导致 json 解析失败.
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());
以上代码返回
"[{"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"}]"
所有 JSON 解析失败.我怎样才能删除这些.
which fails all JSON parsing. How can I remove these.
推荐答案
没有.它没有
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);
}
}
可能有两个问题:
A) 您正在查看调试器的结果.要检查这一点,请将 JsonConvert
放在一个临时变量中(就像我所做的那样)并使用调试器查看它.单击沙漏右侧的箭头并选择 Text Visualizer
.
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
.
或
B) 调用方法正在将对象再次转换为 Json,因此转义了所有内容.
B) The calling method is transforming the object again to Json, so escaping everything.
这篇关于Json.NET 在返回 json 序列化字符串时添加反斜杠的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!