Struggling to deserialize JSON information into a Dictionary with key and value pairs of strings

Looking to convert this JSON data into a Dictionary using native Javascript.

var jsonData = "{"Symptom":[true,true,true],"Action":[true,true],"AllArea":true}";

However, encountering an error when trying to deserialize it with the following code:

Dictionary values = new System.Web.Script.Serialization.JavaScriptSerializer().Deserialize>(jsonData);

An error message is displayed saying

"Type 'System.String' is not supported for deserialization of an array"

Currently working on .Net Framework 3.5. Seeking assistance in resolving this issue.

Answer №1

It seems like a direct conversion to a dictionary may not be possible... I believe the deserializer requires a corresponding type with clear property names and types.

One approach could be to convert to a type, then generate a dictionary as shown below:

public class MyClass
    {
        public List<bool> Symptom { get; set; }
        public List<bool> Action { get; set; }
        public bool AllArea { get; set; }

        public Dictionary<string, List<bool>> GetDictionary()
        {
            var dataDictionary = new Dictionary<string, List<bool>>();
            dataDictionary.Add("Symptom", this.Symptom);
            dataDictionary.Add("Action", this.Action);
            dataDictionary.Add("AllArea", new List<bool>() { AllArea });
            return dataDictionary;
        }
    }

Then you can deserialize and retrieve the dictionary like so:

string inputData = "{\"Symptom\":[true,true,true],\"Action\":[true,true],\"AllArea\":true}";
System.Web.Script.Serialization.JavaScriptSerializer serializer = new System.Web.Script.Serialization.JavaScriptSerializer();
var objectData = serializer.Deserialize<MyClass>(inputData);
var outputDictionary = objectData.GetDictionary();

In any case, it was an interesting question.

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

What is the best way to enclose a block of content with <div> and </div> tags using the append() function?

My goal is to add an outer div container by first appending it, then adding content, and finally appending the closing tag. However, I'm encountering an issue where the div I added at the beginning automatically closes itself, resulting in two separat ...

Eliminating repeating entries in autocomplete results JSON

I am facing a challenge where I have integrated two feature classes, resulting in occasional duplication of results in the autosuggest feature. I am exploring options to detect and display alternatives instead of repeating the same result twice. Check out ...

Inquiring about socket.io: How can an io emit its own signal?

I am currently working on implementing the emit event in an express router, and I'm attempting to pass a global.io variable. However, I've encountered an issue where despite adding the following code: io.emit('join','Tudis' ...

Sorting an array of strings in JavaScript with the help of another array of strings

I am looking for a way to rearrange array1 based on array2. var array1 = ["cat","dog","mouse","elephant","ant","cow","goat","hen"]; var array2 = ["mouse","cow","goat"]; Expected output: var another_array = ["mouse","cow","goat", "bird"--- then rest of ...

What is the best way to generate a Searchstring for the Google AJAX Search API?

Currently, I am using this code to retrieve search results from an API: querygoogle.php: <?php session_start(); // The code below is used to fetch search results from the Google AJAX Search API $url = 'http://ajax.googleapis.com/ajax/services/s ...

The issue of slides overlapping in a Javascript slideshow during auto play mode

I encountered an issue while creating an automatic slideshow with 4 slides. Upon autoplay for the first time, slide 1 overlaps slide 4, as well as slide 2 and 3. This only happens once after the site loads. However, on subsequent playthroughs or when using ...

Postpone reloading automatically if a division is in view

I endeavored to develop a small project aimed at monitoring flights passing over my vicinity. Utilizing the flight-radar24 API python package, I managed to extract the necessary data. Subsequently, I designed a systemd service to execute my python script ...

Is getElementById in JavaScript reliable for multiple calls?

I am attempting to create a table cell that transforms into a textbox upon clicking, allowing for input to be entered and then displayed in the cell. Below is my JavaScript function: $(".cellConsigne").click(function () { var numId = this.id.substrin ...

Working with JSON objects in AngularJS

I have a JSON dataset in the following structure. I need to extract information from the JSON and display it on an HTML table. [region: [name:"", code:""IntradayBalance:{ currency:,Time:,Balance: }.... ], acccountcurrencyBalance:[{ c ...

Is it possible for the $.post function to overwrite variables within the parent function?

Recently, I delved into the world of JavaScript and my understanding is quite limited at this point. So, please bear with me as I learn :-) I am working on a basic booking system that saves dates and user IDs in MySQL. The system checks if a particular da ...

Switch effortlessly between one animation and another with Angular.js

I have two animations named "prev" and "next". Upon clicking the prev button, the "prev" animation should play. Similarly, when you click on the "next" button, the "next" animation should be triggered. I am using ng-class to achieve this behavior. How can ...

Is it possible to pass a class method to an onClick event from within the render method in ReactJS?

Excuse my lack of experience, but I haven't been able to find a solution to this yet. I am attempting to utilize a class method as a callback for the onClick event in my JSX. Below is the code for my App component: import React from 'react&apo ...

Is it possible to await the response of a request in Socket.io with socket.on('answerToRequest')?

Can the following scenario work out? async function checkSocketStatus(){ socket.emit('checkOtherSocketStatus', otherSocketId); await socket.on('responseCheckSocketStatus', (status)=>{ console.log('status'); } ...

Tips on preventing right-click actions in jqGrid

While utilizing onSelectRow in a jqGrid, I have noticed that it functions properly when clicking with the left mouse button. However, when right-clicking, it still triggers the function. My aim is for the right-click to perform its usual action (such as di ...

How can I position 7 images absolutely within a specific div?

I've been working on a website where users can have their avatars displayed using a JS function that loads 7 different images onto the page. These images correspond to different elements such as skin base, hair, eyes, mouth, shirt, shoes, and pants, a ...

Why is adding a div to Facebook posts using JQuery failing due to dynamic loading?

I have been experimenting with the mouseover feature to enhance a Facebook group by adding additional content. Upon testing the DIV class, I realized that after the initial 10 or so instances of DIVs with the class storyInnerWrapper, the text stopped being ...

Only trigger the function for a single bootstrap modal out of three on the current page

I'm facing a challenge on a page where I have 3 bootstrap modals and I need to trigger a function only for one modal while excluding the other two. $("body").on("shown.bs.modal", function() { alert('modal Open'); //this alert should ...

Receiving the error message: `json.decoder.JSONDecodeError: Unexpected token at start of input`

Snippet of Python code: def fetch_response(response_path): response_s3_path = re.sub(config.path_prefix,'',response_path).strip('/') print('== response_s3_path') print(response_s3_path) response_local_path = download_ ...

Iframe Loading at Lightning Speed

I have set up a script to load my iframe, but I noticed that the script loads the iframe content too quickly. Is there a way for me to configure it to preload all CSS images and content in the background before showing the full iframe content? Here is my ...

What steps should I take to implement Node.js for the frontend and Wordpress for the backend?

I was contemplating the idea of utilizing Wordpress as a CMS backend, leveraging its popularity and user-friendly interface, while integrating Node.JS for the front-end. You might be wondering why I would choose this combination and what advantages it offe ...