我有一个ASP MVC项目,其中包含一些Ajax调用。我尝试从jquery/Ajax传递到我的AjaxController(见下面的代码),在控制器中,字符串item接收像这样的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
(您正在发送值数组,而不是单个值) - user3559349List<string[]>
更改为List<string>
。 - Hackerman