An issue occurred while serializing or deserializing, specifically with the JavaScriptSerializer and

I am facing an issue while trying to retrieve images from my database. The process works smoothly with small images, but when attempting to do the same with the default Windows 7 images (Desert, Koala, Penguins, Tulips, etc.), I encounter an error:

"Error during serialization or deserialization using the JSON JavaScriptSerializer. The length of the string exceeds the value set on the maxJsonLength property."

To address this problem, I made changes to my web.config file as follows:

<scripting>
  <webServices>
    <jsonSerialization maxJsonLength="2147483647"/>
  </webServices>
</scripting>

The code snippet used to fetch the images is as follows:

public static byte[] Serialize(object obj)
{
    var binaryFormatter = new BinaryFormatter();
    var ms = new MemoryStream();
    binaryFormatter.Serialize(ms, obj);
    return ms.ToArray();
}


[WebMethod]
public string ObtenerImagen(int id)
{
    DataTable dt = new DataTable();        
    dt = conn.consultarImagen("alertas", id);
    Imagenes img;
    List<Imagenes> lista = new List<Imagenes>();

    for (int i = 0; i < dt.Rows.Count; i++)
    {
        img = new Imagenes();
        img.Id = Convert.ToInt32(dt.Rows[i]["Id"]);
        img.FileName = dt.Rows[i]["FileName"].ToString();
        img.Type = dt.Rows[i]["ContentType"].ToString();
        img.Content = Convert.ToBase64String(Serialize(dt.Rows[i]["Content"]));
        img.IdAlerta = Convert.ToInt32(dt.Rows[i]["IdAlerta"]);
        img.Pie = dt.Rows[i]["PieFoto"].ToString();
        //Populating the list
        lista.Add(img);
        img = null;
    }
    JavaScriptSerializer js = new JavaScriptSerializer();
    string lineas = js.Serialize(lista);
    return lineas;
}

Subsequently, a javascript function is utilized along with Ajax:

 success: function (data) {
        var aRC = JSON.parse(data.d);
        var lineas = "";

        for (var i = 0; i < aRC.length; i++) {
            var id = aRC[i].Id;
            var num = id;
            var rev = aRC[i].FileName;
            var pur = aRC[i].Type;
            var status = aRC[i].Content;
            var imagen = status.substring(36, status.length - 37);
            var owner = aRC[i].IdAlerta;
            var pie = aRC[i].Pie;

            lineas += '<div class="col-lg-3 col-md-4 col-xs-3 thumb marco">';
            lineas += '<a class="thumbnail" href="#">';
            lineas += '<img class="responsive" src="data:image/jpeg;base64,' + imagen + '" />';                    
            lineas += '<p class="text-justify" id="Pie' + i + '">' + pie + '</p>';
            lineas += '</a>';
            lineas += '<span class="btn btn-xs btn-success fa fa-pencil hidden-print" id="EditPie' + i + '"></span>';
            lineas += '<input type="text" class="form-control hidden hidden-print" id="PiePag' + i + '"> <span class="btn btn-xs btn-success fa fa-check hidden hidden-print" id="OkPie' + i + '"></span>';
            lineas += '</div>';
      }
      $('#Imagenes').html(lineas);

I am seeking guidance on how to resolve this issue. Any suggestions would be appreciated.

EDIT: The process works fine with a single image, but encounters an issue when attempting to display multiple images.

Answer №1

One possible solution could be adjusting the maximum JSON length using the instance you have initialized like so:

js.SetMaxJsonLength = Int32.MaxValue;

Have you considered the size of the objects you are trying to include in the JSON? JSON may not handle large objects efficiently, and it might be more effective to load them lazily through AJAX. When dealing with extensive galleries, they often display a loading icon while retrieving specific objects in the background for subsequent items.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Storing an image in MongoDB using Multer as a file from Angular is not working as anticipated

I'm currently dealing with an issue that I believe is not functioning correctly. I installed a library in Angular called cropper.js from https://github.com/matheusdavidson/angular-cropperjs. The frontend code provided by the developer utilizes this li ...

Create seamless communication between Angular application and React build

I am currently engaged in a project that involves integrating a React widget into an Angular application. The component I'm working on functions as a chatbot. Here is the App.tsx file (written in TypeScript) which serves as the entry point for the Rea ...

The AXIOS method in Express.js is designed to return a Promise object that may contain an

I am currently learning ExpressJS and Axios I have created a folder named utils and placed the axios.js file const axios = require('axios'); loadDataPesan=async function(opts){ axios.get('localhost/getData', { params ...

I would like for this message to appear periodically following the initial execution

I have developed a unique welcome feature using HTML and CSS that I would like to showcase intermittently. --------------------------- My Desired Outcome --------------------------- Initially, this feature should be triggered once (when a user first acce ...

efficiency of this algorithm

function checkSubset(array1, array2) { const set1 = new Set(array1); const set2 = new Set(array2); for (const element of set2) { if (!set1.has(element)) { return false; } } return true; } Can we consid ...

Unable to establish a websocket connection with either Amber or NPM, uncertain of the reason

Amber CLI (amberframework.org) - v0.11.3 Crystal 0.27.0 [c9d1eef8f] (2018-11-01) LLVM: 4.0.0 Default target: x86_64-unknown-linux-gnu npm 3.5.2 Attempting to incorporate sockets using Crystal Lang and Amber has hit a snag. Despite following the guidelines ...

How can I effectively capture a change in the hour using Node.js?

Do you know of a more efficient way to monitor datetime changes instead of checking every 10 minutes, potentially firing nearly 10 minutes late? Any alternative solutions that I may have overlooked for this issue? ...

Utilizing deeply nested JSON structure as section.property in a QML listView

My task involves creating a listView that gets its delegate and data from JSON. The challenge I face is setting the section.property based on nested information within the JSON, which is dynamic for each app user. The relevant documentation can be found a ...

Tips for inserting an element into every tier of a multi-layered array

I am faced with a challenging task of assigning an id field to objects within an array that has infinite levels. The rule is simple - for every level, the ID should correspond to the level number starting from 1. { "name": "Anything2&quo ...

The issue of ColdFusion JSON not being handled by JQuery

I am working on a straightforward ColdFusion component that interacts with a database and returns a JSON object <cfcomponent> <cfsetting showdebugoutput="false" enablecfoutputonly="true"> <cffunction name="getNew" access="remote" returntype ...

What is the best way to create a button that can cycle through various divs?

Suppose I want to create a scroll button that can navigate through multiple div elements. Here is an example code snippet: <div id="1"></div> <div id="2"></div> <div id="3"></div> <div id="4"></div> <div ...

Ways to prevent my website from being accessed through the Uc Browser

Is there a way to prevent my website from functioning on UC Browser using HTML or JavaScript? ...

Retrieve and save a JSON file from a specific URL using PHP

I am currently working on a project where I need to extract JSON data from a URL and store it. I was able to retrieve the JSON data using file_get_contents but now I want to save this data in a folder in JSON format. Can someone please help me understand ...

Refresh data with Axios using the PUT method

I have a query regarding the use of the HTTP PUT method with Axios. I am developing a task scheduling application using React, Express, and MySQL. My goal is to implement the functionality to update task data. Currently, my project displays a modal window ...

Tips for retrieving information from two interlinked databases

I have a query to retrieve data from two tables: users and comments. The goal is to fetch comment data and user data based on the commentsenderid . <?php $commentpostid = $_POST['commentpostid']; $sql = "SELECT * FROM comments where comme ...

"The error message "Node JS, MYSQL connection.query is not a valid method" indicates

db_config.js: const mysql = require('mysql'); var connection = mysql.createConnection({ host: 'localhost', user: 'root', password: '', database: 'test' }) connection.connect(function(err) ...

Sending data between two elements when a jQuery event is triggered

As a JavaScript beginner, I am facing an issue where I need to push data from an h1 tag to a textarea. My website is built using WooCommerce and when a visitor clicks on a product, a chat box with the product title opens. Currently, I have successfully p ...

jQuery DataTables covering a CSS-anchored menu bar

My webpage has a pinned navigation menu bar at the top and some tables with interactive features using jQuery's DataTables. However, after implementing jQuery, I encountered an issue where the tables cover the menu when scrolling down, making it uncli ...

The issue with the trigger function in jQuery is specifically affecting Chrome browser

When attempting to load a modal window using a link like , I am encountering issues in Chrome, Safari, and IE. However, Opera and FF are functioning properly. The modal window is being called as an iframe. Other buttons that are supposed to open the modal ...

Creating a Vue application utilizing a function with an unspecified purpose

Looking to create an app with a function that is currently undefined. On the production server, there is a function called __doPostBack which I am calling from my Vue app like this: getLabel(templateName) { __doPostBack(templateName, ""); } Afte ...