2

I have the following json:

[
   {
      "key":"key1",
      "value":"val1"
   },
   {
      "key":"key2",
      "value":"val2"
   }
]

How can I deserialize it into an list/array of NameValuePair<string, string>?

Example:

var json = "[{\"key\":\"key1\",\"value\":\"val1\"},{\"key\":\"key2\",\"value\":\"val2\"}]";

var serializer = new JavaScriptSerializer();
var result = serializer.Deserialize<List<KeyValuePair<string,string>>>(json);

The above code runs but the data inside the list is null. I can extract the array into an List<Object> though.

CodeNotFound
  • 22,153
  • 10
  • 68
  • 69
rboarman
  • 8,248
  • 8
  • 57
  • 87

1 Answers1

8

First off, you should not be using JavaScriptSerializer, Microsoft even explicitly says that in the JavaScriptSerializer docs.

To deserialize an object in Json.NET the syntax is very similar:

var json = "[{\"key\":\"key1\",\"value\":\"val1\"},{\"key\":\"key2\",\"value\":\"val2\"}]";
    
var result = JsonConvert.DeserializeObject<List<KeyValuePair<string,string>>>(json);

Fiddle here

UPDATE

If you are using .NET Core 3 / .NET 5 or .NET 6, the System.Text.Json library is included without an additional dependency.

The syntax for deserializing with that library is:

var result =  JsonSerializer.Deserialize<List<KeyValuePair<string,string>>>(jsonString);
maccettura
  • 10,514
  • 3
  • 28
  • 35