Search code examples
c#json.net

Newtonsoft.Json: Use Dictionary<string, List<string>> as content value for JProperty


I'm using the Newtonsoft.Json package and want to add a Dictionary<string, List<string>> as the content parameter to a JProperty.

For this I created the following sample code

    try {
        Dictionary<string, List<string>> fields = new Dictionary<string, List<string>>()
        {
            {
                "foo",
                new List<string>() { "a", "b" }
            },
            {
                "bar",
                new List<string>() { "c", "d" }
            }
        };
        
        new JProperty(nameof(fields), fields);
    }
    catch (Exception e) {
        Console.WriteLine(e);
    }

I also created a playground for reproduction

https://dotnetfiddle.net/OjyJ5u

Unfortunately I get this exception

System.ArgumentException: Could not determine JSON object type for type System.Collections.Generic.KeyValuePair2[System.String,System.Collections.Generic.List1[System.String]]. at Newtonsoft.Json.Linq.JValue.GetValueType(Nullable`1 current, Object value) at Newtonsoft.Json.Linq.JValue..ctor(Object value) at Newtonsoft.Json.Linq.JContainer.CreateFromContent(Object content)
at Newtonsoft.Json.Linq.JContainer.AddInternal(Int32 index, Object content, Boolean skipParentCheck) at Newtonsoft.Json.Linq.JContainer.AddInternal(Int32 index, Object content, Boolean skipParentCheck) at Newtonsoft.Json.Linq.JContainer.Add(Object content) at Newtonsoft.Json.Linq.JArray..ctor(Object content) at Newtonsoft.Json.Linq.JProperty..ctor(String name, Object content)
at Program.Main()

Does someone know what's wrong with the code?

If that's not possible, are there any suggested workarounds?


Solution

  • You could create JToken from fields to serialize it, by using JToken.FromObject() like :

    JProperty property = new JProperty(nameof(fields), JToken.FromObject(fields));