【发布时间】:2015-10-22 20:52:41
【问题描述】:
我有一个带有一些 Ajax 调用的 ASP MVC 项目,我试图从 jquery/Ajax 传递到我的 AjaxController(参见下面的代码),其中控制器 sting 项正在接收这样的 json 字符串
"[\n \"1002\",\n \"1003\"\n]"
我在控制器中收到此错误(请参阅下面的代码,其中注释标识了错误)
Newtonsoft.Json.JsonSerializationException: Error converting value "1002" to type 'System.String[]'. Path '[0]', line 2, position 9. ---> System.ArgumentException: Could not cast or convert from System.String to System.String[]. at Newtonsoft.Json.Utilities.ConvertUtils.EnsureTypeAssignable(Object value, Type initialType, Type targetType) at Newtonsoft.Json.Utilities.ConvertUtils.ConvertOrCast(Object initialValue, CultureInfo culture, Type targetType) at Newtonsoft.Json.Serialization.JsonSerializerInternalReader.EnsureType(JsonReader reader, Object value, CultureInfo culture, JsonContract contract, Type targetType) ...(continue)
这是我的 Json/Jquery 创建函数
function SaveObservations() {
var SerSel = $("#ServiceIdSelect2").val();
var obs = $("#observation").val();
var itemsX = [];
if (obs == "") {
mostrar_alert_ui("Validation message", "Observation cannot be null", 350);
} else {
//Start json creation
$("#ItemsPieces > input:checked").each(function () {
var id = $(this).val();
itemsX.push(id);
});
var itemsY = JSON.stringify(itemsX, null, 2);
//End json creation
Funciones_Ajax_conAlert("/Ajax/SendEmailItemsToClient/", { proyecto: SerSel, items: itemsY, observation: obs }, CloseObservations);
}
}
这是我的控制器给出错误的地方
public JsonResult SendEmailItemsToClient(int proyecto, string items, string observation)
{
object data = null;
try
{
List<string[]> datax1 = JsonConvert.DeserializeObject<List<string[]>>(items); //Here is the issue Aqui tengo el problema
foreach (var item in datax1)
{
string test = item.ToString();
}
string mensaje = "";
int ProjectIdx = proyecto;
bool resp = CorreccionesController.SendItemsDifferentsToClient(ProjectIdx, mensaje);
if (resp) {
data = new
{
success = true,
titulo = "Notification",
mensaje = "A message explaining why the different items selected are used had been sent"
};
}
else
{
data = new
{
success = false,
titulo = "Notification",
mensaje = "The observation is Saved but the email couldn't be send, please contact support"
};
}
}
catch (Exception ex)
{
data = new
{
success = false,
titulo = "ERROR",
mensaje = ex.ToString()
};
}
return Json(data, JsonRequestBehavior.AllowGet);
}
问题是如何在不收到错误的情况下迭代该 json 字符串?
【问题讨论】:
-
将参数更改为
string[] items(您发送的是一组值,而不是单个值) -
将
List<string[]>更改为List<string> -
@Hackerman 谢谢我用你的解决方案解决了,你能否用更完整的答案回答这个问题,以便我接受并给你+1?
-
好的,我会尽快提供答案。
-
@RicardoRios,完成......请检查我的答案。
标签: c# jquery asp.net json asp.net-mvc