NewtonSoft JsonConvert SerializeObject Object Escape Chars字典

时间:2016-10-19 11:47:22

标签: c# json wcf dictionary json.net

我在WCF中使用关于转义字符的JsonConvert.SerializeObject方法时遇到了一些麻烦。我的web方法返回一个Stream,如下所示:

 return new MemoryStream(Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(myObject)));

除了myObject的一个属性是<string, object>的词典之外,这个工作正常。所有简单类型都正确序列化,但是当我尝试将自定义类添加为值时,我得到返回的类型而不是数据。实现这一点来自于我的自定义类上的序列化器调用.ToString我尝试用它来覆盖它:

public override string ToString()
    {
        return JsonConvert.SerializeObject(this);
    }

但是返回的数据现在包含转义字符

{       
    "my_dictionary":    {
      "elem_1": "{\"Prop1\":null,\"Prop2\":3}",
      "elem_2": "{\"Prop1\":null,\"Prop2\":3}",
      "int_property" : 123
   }
}

关于如何避免我的自定义类以这种方式转义并以数组形式返回的任何想法?

提前谢谢,马特

2 个答案:

答案 0 :(得分:0)

我使用JavaScriptSerializer(只需将“Object”替换为您的自定义类)

string nameFile = "Test.xml";
bool newFile = false;


if (!File.Exists(nameFile))
{
    newFile = true;
    XmlWriterSettings xmlWriterSettings = new XmlWriterSettings();
    xmlWriterSettings.Indent = true;
    xmlWriterSettings.NewLineOnAttributes = true;

    xmlWriter.WriteStartDocument();
    xmlWriter.WriteStartElement("School");

    xmlWriter = XmlWriter.Create("Test.xml", xmlWriterSettings))
}
else
{
    doc = new XmlDocument();
    doc.Load(nameFile);

    // Create a XPathNavigator
    // You can go where you want to add
    // In this case it is just after last child of the roor
    XPathNavigator navigator = doc.CreateNavigator();     

    navigator.MoveToChild("School", "");
    xmlWriter = navigator.AppendChild();
}

// From here you can work only with xmlWriter,
// One will point on a file and the other on the stream of xmlDocument
// So you will need to save the document in the second choise

xmlWriter.WriteStartElement("Student");
xmlWriter.WriteElementString("FirstName", firstName);
xmlWriter.WriteElementString("LastName", lastName);
xmlWriter.WriteEndElement();


// End document / close or save. 
if (newFile)
    xmlWriter.WriteEndDocument();

xmlWriter.Close();

if (!newFile)
    doc.Save(nameFile);

并使用“res”值获取此格式:

using System.Web.Script.Serialization;

List<Object> list = new List<Object>();

JavaScriptSerializer jss = new JavaScriptSerializer();

string res = jss.Serialize(list);

答案 1 :(得分:0)

我已经意识到代码中存在错误。被序列化的类实际上返回了一个Dictionary,将对象转换为字符串导致了我观察到的行为,实际上序列化器完全能够正确地序列化对象。