JsonResult将Json解析对象作为空数组集合发送到浏览器[[]],[[]]

时间:2018-02-06 14:38:59

标签: json asp.net-mvc

我试图向JsonResult对象添加一个已解析的Json字符串,但我无法做到,浏览器中的解析器对象显示为:

    public JsonResult AjaxStandardGet(int id)
    {
        Standard ec = db.Standard.FirstOrDefault(s => s.IdStandard == id);

        // inside filter: { "KeyDynamic1": "Value1", "KeyDynamic2": [ "AAA", "DDD"] }
        var filter = JsonConvert.DeserializeObject(ec.Filter);

        return Json(new
        {
            ec.IdStandard,
            ec.Description,
            filter,
            ec.Observations,
            Services = ec.StandardServices.Select(s => new {
                s.IdStandardServices,
                Tecnology = s.Tecnology?.Nombre,
                ServiceType = s.ServiceType?.Description,
                s.Quantity,
                s.Cost,
                Options = (!string.IsNullOrEmpty(s.Options) ? s.Options.Split(',') : null),
                Total = s.Quantity * s.Cost
            }),
            Success = true
        });
    }

这是完整的代码

Dictionary<string, object> filter = JsonConvert.DeserializeObject<Dictionary<string, object>>(ec.Filter);

我无法创建模型对象,因为过滤器并非总是相同。

我试过了:

"filter":{"KeyDynamic1":"Value1","KeyDynamic2":[[],[]]}

我得到了

{{1}}

1 个答案:

答案 0 :(得分:1)

我建议您JTokendynamic

JToken filter = JToken.Parse(ec.Filter);

dynamic filter = JsonConvert.DeserializeObject<dynamic>(ec.Filter);

以下是fiddle

更新

JavaScriptSerializer似乎无法做到。因此,您可以使用Newtonsoft.Json序列化结果并将其作为字符串返回:

var result = new
    {
        ec.IdStandard,
        ec.Description,
        filter,
        ec.Observations,
        Services = ec.StandardServices.Select(s => new {
            s.IdStandardServices,
            Tecnology = s.Tecnology?.Nombre,
            ServiceType = s.ServiceType?.Description,
            s.Quantity,
            s.Cost,
            Options = (!string.IsNullOrEmpty(s.Options) ? s.Options.Split(',') : null),
            Total = s.Quantity * s.Cost
        }),
        Success = true
    };
var json = JsonConvert.SerializeObject(result);
return Content(json, "application/json");