问题描述
我有以下功能
public static string Serialize<T>(T obj)
{
string returnVal = "";
try
{
DataContractJsonSerializer serializer = new DataContractJsonSerializer(obj.GetType());
using (MemoryStream ms = new MemoryStream())
{
serializer.WriteObject(ms, obj);
returnVal = Encoding.UTF8.GetString(ms.ToArray());
}
}
catch (Exception /*exception*/)
{
returnVal = "";
}
return returnVal;
}
当obj包含一个字符串字段,其中包含带有'/'的字符串,例如:
when obj contains a string field which contains a string with '/' s such as :
" A4AAAAAAAAAAAAA ///////"
当调用WriteObject并稍后将其变为字符串(使用ToArray())时,它变为(当JSON时)
when WriteObject is called and later made into a string (with ToArray()) it becomes (when JSON)
" A4AAAAAAAAAAAAA \ / \ / \ / \ / \ / \ / \ /"
我怎样才能避免这种情况,并且不为每个'\'添加'/'?
推荐答案
我建议您使用javascriptSerializer或Newtonsoft.Json,这可能优雅地解决问题。
我做了一个演示,希望它对你有用。
I suggest you use the javascriptSerializer or Newtonsoft.Json, which could solve the problem gracefully.
I have made a demo, wish it is useful to you.
class Program
{
static void Main(string[] args)
{
Product p = new Product()
{
Id = 1,
Name = "Apple////"
};
var result = Serialize<Product>(p);
Console.WriteLine(result);
}
public static string Serialize<T>(T obj)
{
string result = "";
try
{
JavaScriptSerializer serializer = new JavaScriptSerializer();
result = serializer.Serialize(obj);
//JsonSerializer serializer = new JsonSerializer();
//StringBuilder sb = new StringBuilder();
//TextWriter tw = new StringWriter(sb);
//serializer.Serialize(tw, obj);
//result = sb.ToString();
}
catch (Exception)
{
result = "";
}
return result;
}
}
public class Product
{
public int Id { get; set; }
public string Name { get; set; }
}
结果。
如果您有任何疑问,请随时与我们联系。
Feel free to let me know if you have any questions.
最好的问候
亚伯拉罕
这篇关于处理'/'时DataContracJsonSerializer和WriteObject的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!