【问题标题】:pass object to WebMethod with Dictionary<string, int> paramter使用 Dictionary<string, int> 参数将对象传递给 Web 方法
【发布时间】:2013-02-22 11:35:50
【问题描述】:

我有这个错误 无法将类型 \u0027System.String\u0027 的对象转换为类型 \u0027System.Collections.Generic.Dictionary2[System.String,System.Int32]\u0027","StackTrace":" at System.Web.Script.Serialization.ObjectConverter.ConvertObjectToTypeInternal(Object o, Type type, JavaScriptSerializer serializer, Boolean throwOnError, Object&amp; convertedObject)\r\n at System.Web.Script.Serialization.ObjectConverter.ConvertObjectToTypeMain(Object o, Type type, JavaScriptSerializer serializer, Boolean throwOnError, Object&amp; convertedObject)\r\n at System.Web.Script.Serialization.ObjectConverter.ConvertObjectToType(Object o, Type type, JavaScriptSerializer serializer)\r\n at System.Web.Script.Services.WebServiceMethodData.StrongTypeParameters(IDictionary2 rawParams)\r\n 在 System.Web.Script.Services.WebServiceMethodData.CallMethodFromRawParams(对象目标,IDictionary@987654322 @2 rawParams)\r\n 在 System.Web.Script.Services.RestHandler.ExecuteWebServiceCall(HttpContext context, WebServiceMethodData methodData)","ExceptionType":"System.InvalidOperationException

当我使用 Dictionary 将数组传递给 WebMethod 时

【问题讨论】:

  • 您是否尝试在 webmehtod/webapi 项目的参数中传递 Dictionary 对象??
  • 不,我让 forloop 在 forloop 中创建新对象以将其推送到数组中并生成 JSON.stringify(array) 但得到相同的错误

标签: javascript jquery asp.net json json.net


【解决方案1】:

如果它是 webapi 的 webmethod 那么你不能将列表或字典类型的对象传递给方法,你只会假设传递字符串参数,传递这个对象你需要将它们序列化为字符串然后你可以反序列化使用该字符串将它们返回到您的列表或字典对象。

Webmethod 消费代码:

Dictionary<string,int> objstring = new Dictionary<string,int>
var serializer = new JavaScriptSerializer();
var serializedstring = serializer.Serialize(objstring);

然后在参数中传递序列化字符串。

反序列化时做同样的事情,只需从 webapi 方法中的序列化程序对象调用反序列化方法。

希望对你有帮助。

【讨论】:

  • 我想通过 json 函数 [WebMethod] public string save(Dictionary para) { } 将 Dictionary 传递给 WebMethod
猜你喜欢
  • 2012-05-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-07-02
  • 2012-12-02
  • 2013-11-26
相关资源
最近更新 更多