true

I'm trying to return a large set o json (about 2MB) but the web api returns the error:

"Error during serialization or deserialization using the JSON JavaScriptSerializer. The length of the string exceeds the value set on the maxJsonLength property". I've tried configure the maxJsonLength property in the web.config but without success.

I've seen another answers in the stackoverflow but all related to a regular .NET MVC Controller and not an ApiController.

It's possible to bypass the internal JavaScriptSerializer maxJsonLenght or by doing some custom JsonSerializerType format?

upvote
  flag
Hi @Coastpear what version of webapi are you using? depending on which version you are using the override will change a little. – BMac
upvote
  flag
I'm using version 5.1.0.0 – Coastpear

3 Answers 11

Have you tried setting the MaxJsonDeserializerMembers in web.config?

<appSettings>
      <add key="aspnet:MaxJsonDeserializerMembers" value="1000" />
    </appSettings>
upvote
  flag
Yes, it didn't work because that config it's for asp.net runtime and not for internal javascriptSerializer usage. This "internal javascriptSerializer" doesn't look for any config in the web.config. But thanks anyway. :) – Coastpear

Depending on just how large the JSON payload becomes, you may have to stream the response. See this blog post. In short that blog post can be summarised by the below code:

[HttpGet]
public HttpResponseMessage PushStreamContent()
{
    var response = Request.CreateResponse();

    response.Content = 
    new PushStreamContent((stream, content, context) =>
    {
        foreach (var staffMember in _staffMembers)
        {
            var serializer = new JsonSerializer();
            using (var writer = new StreamWriter(stream))
            {
                serializer.Serialize(writer, staffMember);
                stream.Flush();
            }
        }
    });

    return response;
}
upvote
  flag
It didn't resolve my problem but lead me to a possible resolution, using StringContent instead I can flush the content to the browser the only problem is that it not comes with the content type "applicataion/json" but with "text/plaintext" – Coastpear

Thanks @BMac for your help, you lead me to a solution that works.

[HttpGet]
//ResponseType it's for ApiDescription successfully generates the helper page with the right type since i'm returning a plain/text content
[ResponseType(typeof(YourType))]
public async Task<HttpResponseMessage> GetLargeJsonDataWithWebAPI()
{
    String url = "someUrl";
    String jsonData = EnvironmentUrlHelper.GetJsonResourseAsync<YourType>(url);


    var response = Request.CreateResponse();
    response.Content = new StringContent(JsonConvert.SerializeObject(rsp));

    return response;
}

Not the answer you're looking for? Browse other questions tagged or ask your own question.