Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Serialize Dictionary<int,object> using JSON.net?

Tags:

People also ask

Can JSON serialize dictionary?

Json can't serialize Dictionary unless it has a string key. The built-in JSON serializer in . NET Core can't handle serializing a dictionary unless it has a string key.

Can dictionary be serialized in C#?

NET objects is made easy by using the various serializer classes that it provides. But serialization of a Dictionary object is not that easy. For this, you have to create a special Dictionary class which is able to serialize itself. The serialization technique might be different in different business cases.

Can we convert dictionary to JSON in C#?

Simple One-Line Answer This code will convert any Dictionary<Key,Value> to Dictionary<string,string> and then serialize it as a JSON string: var json = new JavaScriptSerializer(). Serialize(yourDictionary. ToDictionary(item => item.

How is a dictionary represented in JSON?

Introducing JSON JSON is a way of representing Arrays and Dictionaries of values ( String , Int , Float , Double ) as a text file. In a JSON file, Arrays are denoted by [ ] and dictionaries are denoted by { } .


I'm trying to use JSON.net to serialize a Dictionary.

Using

JsonConvert.SerializeObject(theDict);

Here is my result

{
  "1": {
    "Blah1": false,
    "Blah2": false,
    "Blah3": "None",
    "Blah4": false
  },
  "2": {
    "Blah1": false,
    "Blah2": false,
    "Blah3": "None",
    "Blah4": false
  },
  "3": {
    "Blah1": false,
    "Blah2": false,
    "Blah3": "None",
    "Blah4": false
  },
  ...
  ...
  ...
}  

Is there a way to serialize this dictionary such that the keys are rendered as valid javascript variables?

I am also open to other strategies of serializing the dictionary.