Santiago
Santiago

Reputation: 2330

JsonResult is sending Json parsed object as empty array collection to browser [[]],[[]]

I'm trying to add to the JsonResult object a parsed Json string, but I couldn't do it, the parser object in the browser is shown as:

"filter":[[[]],[[[],[]]]]

This is the full code

    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
        });
    }

I can't create the model object because the filters are not allways the same.

I tried this:

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

And I get

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

Upvotes: 0

Views: 343

Answers (1)

Roman Koliada
Roman Koliada

Reputation: 5102

I suggest you to JToken or dynamic:

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

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

Here is working fiddle.

Update

It seems that JavaScriptSerializer is not able to do it. So you can serialize your result using Newtonsoft.Json and return it as a string:

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");

Upvotes: 1

Related Questions