ASP.NET的JavaScriptSerializer需要的Htt presponse?
看来,System.Web.Script.Serialization.JavascriptSerializer类尝试获取当前请求,presumably采取适当的字符编码型Htt presponse。
It appears that the System.Web.Script.Serialization.JavascriptSerializer class tries to obtain the HttpResponse for the current request, presumably to apply appropriate character encoding.
然而,这意味着,当你与范围没有HttpContext的使用类,它与下面的异常+堆栈跟踪打击了:
However this means that when you to to use the class with no HttpContext in scope, it blows up with the following exception + stack trace:
[HttpException (0x80004005): Response is not available in this context.]
System.Web.HttpContext.get_Response() +8753496
System.Web.Util.HttpEncoder.get_Current() +39
System.Web.HttpUtility.JavaScriptStringEncode(String value, Boolean addDoubleQuotes) +13
System.Web.Script.Serialization.JavaScriptSerializer.SerializeString(String input, StringBuilder sb) +31
System.Web.Script.Serialization.JavaScriptSerializer.SerializeCustomObject(Object o, StringBuilder sb, Int32 depth, Hashtable objectsInUse, SerializationFormat serializationFormat) +240
System.Web.Script.Serialization.JavaScriptSerializer.SerializeValueInternal(Object o, StringBuilder sb, Int32 depth, Hashtable objectsInUse, SerializationFormat serializationFormat) +1355
System.Web.Script.Serialization.JavaScriptSerializer.SerializeValue(Object o, StringBuilder sb, Int32 depth, Hashtable objectsInUse, SerializationFormat serializationFormat) +194
System.Web.Script.Serialization.JavaScriptSerializer.Serialize(Object obj, StringBuilder output, SerializationFormat serializationFormat) +26
System.Web.Script.Serialization.JavaScriptSerializer.Serialize(Object obj, SerializationFormat serializationFormat) +74
System.Web.Script.Serialization.JavaScriptSerializer.Serialize(Object obj) +6
我不能返工code以这样一种方式,以保证有效的HttpContext的存在。如何避免这种情况的任何想法?可能字符串类型的定制JavascriptConverter是一个强大的解决方案?
I cannot rework the code in such a way as to guarantee the existence of a valid HttpContext. Any ideas on how to avoid this? Might a custom JavascriptConverter for the String type be a robust solution?
感谢
帕斯卡尔
据我所知JavaScriptSerializer不需要任何的HttpContext并在控制台应用程序工作完全正常:
AFAIK JavaScriptSerializer doesn't require any HttpContext and works perfectly fine in a console application:
class Program
{
static void Main(string[] args)
{
string json = new JavaScriptSerializer().Serialize(new { Bar = "foo" });
Console.WriteLine(json);
}
}
您也可以尝试 Json.NET 。