Home > database >  deserializing Keyvaluepair and Dictionary with .NET 6
deserializing Keyvaluepair and Dictionary with .NET 6

Time:02-01

I have an issue with the following minimal code:

[Fact]
public void DeserializeKeyValuePair()
{
    string text = "{\"offer\": 12432515239}";
    KeyValuePair<string, long> test = JsonSerializer.Deserialize<KeyValuePair<string, long>>(text);
}

In .NET 7, this code works as expected.
.NET 6 in turn throws an error that the keyvaluepair could not be converted.

System.Text.Json.JsonException : 
The JSON value could not be converted to System.Collections.Generic.KeyValuePair`2[System.String,System.Int64]. 
Path: $.offer | LineNumber: 0 | BytePositionInLine: 9.

Unfortunately, I cannot upgrade my project to .NET 7 due to incompatibilities with another important library.

Perhaps Newtonsoft.Json can do that but I am trying to keep third party libraries to an absolute minimum. I'm also surprised that I do not find more references of this issue in the internet.

Is there a way to resolve the issue?

Update:

the string seems to deserialize into null with .NET 7, which is still unexpected. But, it does not crash. The main purpose is to deserialize dictionaries from server api responses.

The solution was, according to Guru Stron to install the nuget package. Check out his answer for that.

CodePudding user response:

Deserialization to KeyValuePair<,> resulting in exception seems like a bug, but you can use Dictionary<string, long>:

KeyValuePair<string, long> test =
    JsonSerializer.Deserialize<Dictionary<string, long>>(text).First();

Or create a custom converter. Another approach you can try is to install System.Text.Json nuget with latest version manually.

P.S.

In .NET 7, this code works as expected.

Or not, I would say that expected here is up for debate (compared to Dictionary<,> handling), though Newtonsoft.Json and System.Text.Json work the same in .NET 7:

KeyValuePair<string, long> test = 
    JsonSerializer.Deserialize<KeyValuePair<string, long>>(text);
// test = JsonConvert.DeserializeObject<KeyValuePair<string, long>>(text);
Console.WriteLine(test.Key ?? "null"); // prints "null"
Console.WriteLine(test.Value); // prints "0"
  • Related