Newtonsoft.Json 反序列化字典Key为Vector时解决方案

 

 

栗子:

   using Test = Dictionary<Vector2Int, Vector2>;
    public class NewBehaviourScript : MonoBehaviour
    {
        private void Awake()
        {
            Test list = new Test();
            list.Add(Vector2Int.zero, Vector2Int.one);
            list.Add(new Vector2Int(9999, 6666), Vector2Int.one);
            
            var jsonSerializerSettings = new JsonSerializerSettings()
            {
                //防递归
                ReferenceLoopHandling = ReferenceLoopHandling.Ignore,
                //自定义类型转换器
                Converters = { new DictionaryJsonConverter<Vector2Int, Vector2>() }
            };

            var json = JsonConvert.SerializeObject(list, jsonSerializerSettings);
            var o = JsonConvert.DeserializeObject<Test>(json, jsonSerializerSettings);

            foreach (var item in o)
            {
                Debug.Log($"{item.Key}====={item.Value}");
            }
        }
    }

 

字典转换器:

/// <summary>
/// 字典类型转换器
/// </summary>
/// <typeparam name="Key"></typeparam>
/// <typeparam name="Value"></typeparam>
public class DictionaryJsonConverter<Key, Value> : JsonConverter<IDictionary<Key, Value>>
{
    public override IDictionary<Key, Value> ReadJson(JsonReader reader, Type objectType, IDictionary<Key, Value> existingValue, bool hasExistingValue, JsonSerializer serializer)
    {
        var dictionary = new Dictionary<Key, Value>();

        while (reader.Read())
        {
            if (reader.TokenType == JsonToken.EndObject)
            {
                return dictionary;
            }

            if (reader.TokenType != JsonToken.PropertyName)
            {
                throw new JsonException();
            }

            //序列化Key
            string propertyName = reader.Value.ToString();
            var key = JsonConvert.DeserializeObject<Key>(propertyName);

            //序列化Value
            reader.Read();
            var value = serializer.Deserialize<Value>(reader);

            dictionary.Add(key, value);
        }

        throw new JsonException();
    }

    public override void WriteJson(JsonWriter writer, IDictionary<Key, Value> value, JsonSerializer serializer)
    {
        writer.WriteStartObject();
        foreach (var item in value)
        {
            var propertyName = JsonConvert.SerializeObject(item.Key,new JsonSerializerSettings() { ReferenceLoopHandling= ReferenceLoopHandling.Ignore});
            writer.WritePropertyName(propertyName);
            serializer.Serialize(writer, item.Value);
        }
        writer.WriteEndObject();
    }
}

 

  • 2
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

小鱼游戏开发

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值