2

I'm trying to return a dynamic json array to the client side in mvc.

So far I have

            var a = 1;
            var b = 10;
            var jsonArray = new JArray();

            for (var i = 1; i < 5; i++)
            {
                var json = new JObject();
                json.Add("field" + a, b);

                jsonArray.Add(json);
                a++;
                b++;
            }

            return Json(jsonArray);

this returns to the client

[[[[]]]]

I have tried converting the JsonArray to a string first and setting it to have no formatter, but that doesn't return valid json according to fiddler.

I'd expect the result to be soemething like:

[{field1:10},{field2:11},{field3:12}]

Can anyone point out what I'm doing wrong

1 Answer 1

2

This passed muster in Fiddler:

return Json(new { JsonArray = jsonArray.ToString() });

Fiddler seems to need JSON objects in the form { "FieldName": value }, hence my creation of an anonymous object. You could use any name in place of JsonArray.

Simply returning Json(jsonArray) isn't going to work because jsonArray will have an underlying representation that is dissimilar to your desired output, hence the output you are seeing when you serialize it.

Sign up to request clarification or add additional context in comments.

3 Comments

This filled my response with \r\n characters. I need to return results without them.
@bcr if your action method return type is 'object' and you return JArray mvc will serialize jarray (which won't be the json it contains). If your action returns JsonResult as answered by nick_w the tostring will mean the entire jarray is just an escaped string. You'd need to use ContentResult with contentType 'application/json' and the jarray.ToString() as the content value
HttpResponseMessage for api controllers

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.