【问题标题】:how to serialize a list to json without the char "\"? [duplicate]如何在没有字符“\”的情况下将列表序列化为 json? [复制]
【发布时间】:2018-09-27 21:04:11
【问题描述】:

我正在尝试将对象列表序列化为 json,但在 json 中,所有数据成员都被“\”包围。 比如我的对象是:

public class ResObject
{
    public double productPrice { get; set; }
    public string productName { get; set; }
    public double distance { get; set; }
    public string fullAddress { get; set; }
    public string fullStoreName { get; set; }
    public string promotion { get; set; }
}

结果 json 为:

"[{\"productPrice\":4,\"productName\":\"Milk\",\"distance\":0,\"fullAddress\":\"UK\",\"fullStoreName\":\"LiaStore\",\"promotion\":null},...]"

我使用了这个代码:

string json = JsonConvert.SerializeObject(Products, Formatting.None);

var json = new JavaScriptSerializer().Serialize(Products);

    //Create a stream to serialize the object to.  
    MemoryStream ms = new MemoryStream();

    // Serializer the User object to the stream.  
    DataContractJsonSerializer ser = new DataContractJsonSerializer(typeof(List<ResObject>));
    ser.WriteObject(ms, Products);
    byte[] json = ms.ToArray();
    ms.Close();

    return Encoding.UTF8.GetString(json, 0, json.Length);

但它没有帮助:(

(产品为List&lt;ResObject&gt; Products

谢谢!

编辑:我修复了它,问题是我序列化了列表并返回了它,因为它是 WebAPI,这就是问题所在。解决方法是返回列表并删除序列化。

【问题讨论】:

标签: c# json jsonserializer


【解决方案1】:

让我猜猜……你在调试器中查看了字符串。 只需将其打印到控制台或将其写入文件,您就会看到那些“\”已经消失了。

这只是调试器中显示的转义字符。

这样,你就可以在 s 字符串中放入一个‘“’。

【讨论】:

  • 重复的@Andreas 中显示的信息是否相同?
  • 我不知道...我在标记之前写了答案。
猜你喜欢
  • 1970-01-01
  • 2012-05-07
  • 1970-01-01
  • 2011-12-29
  • 1970-01-01
  • 1970-01-01
  • 2016-02-04
  • 2010-12-29
相关资源
最近更新 更多