Deserialization issue using a custom resolver with IDictionary<Mycustomclass, List<string>>

橙三吉。 提交于 2020-01-23 08:18:04

问题


Problem:

I have a class Foo containing an IDictionary<MyCustomClass, List<string>>. I am using a custom ContractResolver as shown in this answer so that my dictionary will serialize as an array of objects containing "Key" and "Value" properties. That part works fine. However, when I try to deserialize the JSON back into Foo using the same resolver, I get an error as shown below.

Error:

Run-time exception (line 46): Cannot deserialize the current JSON array (e.g. [1,2,3]) into type 'System.Collections.Generic.IDictionary2[mycustomclass,System.Collections.Generic.List1[System.String]]' because the type requires a JSON object (e.g. {"name":"value"}) to deserialize correctly.

To fix this error either change the JSON to a JSON object (e.g. {"name":"value"}) or change the deserialized type to an array or a type that implements a collection interface (e.g. ICollection, IList) like List that can be deserialized from a JSON array. JsonArrayAttribute can also be added to the type to force it to deserialize from a JSON array.

Path 'Dict2', line 12, position 13.

Dotnetfiddle:

https://dotnetfiddle.net/BKaKab

My code:

using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using Newtonsoft.Json;
using Newtonsoft.Json.Serialization;



public class mycustomclass
{
    public string name {get;set;}
    public List<string> Productlist {get;set;}
    public List<string> SelectedItems{get;set;}
}


public class Program
{
    public static void Main()
    {
        mycustomclass omycustomclass = new mycustomclass{name = "Test",Productlist =  new string[]{"Product1","Product2","Product3"}.ToList(), SelectedItems = new string[]{"Item1","Item2","Item3"}.ToList()};
        mycustomclass omycustomclass2 = new mycustomclass{name = "Test",Productlist =  new string[]{"Product4","Product5","Product6"}.ToList(), SelectedItems = new string[]{"Item4","Item5","Item6"}.ToList()};

        Foo foo = new Foo();
        foo.Dict = new Dictionary<string, string>();
        foo.Dict.Add("Gee", "Whiz");
        foo.Dict.Add("Fizz", "Bang");

        Dictionary<mycustomclass, List<string>> custom = new Dictionary<mycustomclass, List<string>>();     
        custom.Add(omycustomclass, new string[]{"l1","l2","l3"}.ToList());
        custom.Add(omycustomclass2, new string[]{"l4","l5","l6"}.ToList());
        foo.Dict2 = custom;


        JsonSerializerSettings settings = new JsonSerializerSettings();
        settings.Formatting = Formatting.Indented;
        settings.ContractResolver = new DictionaryAsArrayResolver();

        // serialize
        string json = JsonConvert.SerializeObject(foo, settings);
        Console.WriteLine(json);
        Console.WriteLine();

        // deserialize
        foo = JsonConvert.DeserializeObject<Foo>(json, settings);
        foreach (var kvp in foo.Dict)
        {
            Console.WriteLine(kvp.Key + ": " + kvp.Value);
        }

    }

    class Foo
    {
        public Dictionary<string, string> Dict { get; set; }
        public IDictionary<mycustomclass, List<string>> Dict2 { get; set; }
    }
}

class DictionaryAsArrayResolver : DefaultContractResolver
{
    protected override JsonContract CreateContract(Type objectType)
    {
        if (objectType.GetInterfaces().Any(i => i == typeof(IDictionary) || 
            (i.IsGenericType && i.GetGenericTypeDefinition() == typeof(IDictionary<,>))))
        {
            return base.CreateArrayContract(objectType);
        }

        return base.CreateContract(objectType);
    }
}

JSON:

{
  "Dict": [
    {
      "Key": "Gee",
      "Value": "Whiz"
    },
    {
      "Key": "Fizz",
      "Value": "Bang"
    }
  ],
  "Dict2": [
    {
      "Key": {
        "name": "Test",
        "Productlist": [
          "Product1",
          "Product2",
          "Product3"
        ],
        "SelectedItems": [
          "Item1",
          "Item2",
          "Item3"
        ]
      },
      "Value": [
        "l1",
        "l2",
        "l3"
      ]
    },
    {
      "Key": {
        "name": "Test",
        "Productlist": [
          "Product1",
          "Product2",
          "Product3"
        ],
        "SelectedItems": [
          "Item1",
          "Item2",
          "Item3"
        ]
      },
      "Value": [
        "l1",
        "l2",
        "l3"
      ]
    }
  ]
}

Can someone help me get it working?


回答1:


Not sure if it's the best way, but it solves your problem. Create a converter

internal class MyConverter : CustomCreationConverter<IDictionary<CustomClass, List<String>>>
{
    public override IDictionary<CustomClass, List<String>> Create(Type objectType)
    {
        return new Dictionary<CustomClass, List<String>>();
    }

    public override bool CanConvert(Type objectType)
    {
        return objectType == typeof (object) || base.CanConvert(objectType);
    }
}

Add it to your settings:

var settings = new JsonSerializerSettings
    {
        Formatting = Formatting.Indented,
        ContractResolver = new DictionaryAsArrayResolver(),
        Converters = new JsonConverter[] {new MyConverter()}
    };

Enjoy.

Sample



来源:https://stackoverflow.com/questions/32473308/deserialization-issue-using-a-custom-resolver-with-idictionarymycustomclass-li

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!