仿制药的JSON序列化 [英] JSON serialization of generics

查看:125
本文介绍了仿制药的JSON序列化的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个看起来像这样的类:

I have a class that looked like this:

public class MyData : IList<Tuple<double,double>>



这个想法是,你必须对值的列表。就这么简单。但我想这是序列化,使得它看起来像一个double数组的数组(即双击[] [] ),而不是一个元组列表。它应该是这样的,当序列化:

The idea being that you have a list of pairs of values. Simple enough. But I wanted this to be serialized such that it looks like an array of an array of doubles (i.e. double[][]) rather than a list of tuples. It should look like this when serialized:

[[1,1],[2,2],[3,3]]

所以,我创建了一个简单的 JsonConverter 的将做到这一点。它看起来像这是一个非常简单的 WriteJson 方法:

So I created a simple JsonConverter that will do it. It has a very simple WriteJson method that looks like this:

public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
{
    var obj = value as MyData;
    double[][] dataArray = (from dp in obj._data
                            select new[] { dp.Item1, dp.Item2 }).ToArray();
    var ser = new JsonSerializer();
    ser.Serialize(writer, dataArray);
}

和我装点迈德特与适当的属性:

And I decorate MyData with the appropriate attribute:

    [JsonConverter(typeof(MyDataJsonConverter))]
    public class MyData: IList<Tuple<double,double>>

和一切工作正常。但是现在,我要扩展这个,让迈德特通用:

And everything works fine. Now however, I want to extend this and make MyData generic:

    public class MyData<S,T>: IList<Tuple<S,T>>



这是被我遇到的问题。起初,我试图使 MyDataJsonConverter 也通用:

   [JsonConverter(typeof(MyDataJsonConverter<S,T>))]
   public class MyData<S,T>: IList<Tuple<S,T>>



但是,这是不允许的,因为你不能与属性使用泛型。

But that isn't allowed because you can't use generics with attributes.

所以我必须保持 MyDataJsonConverter 非通用的,但我需要弄清楚如何打平我的收藏元组到一个数组(想必对象[] [] 现在)这样,当我序列化我的数据会看起来像:

So I have to keep MyDataJsonConverter non-generic, but I need to figure out how to flatten my collection of tuples into an array (presumably of object[][] now) such that when I serialize my data would look like:

[[1,2],[2,3]]

[["foo":1],["bar":2]]

甚至是:

[["foo":"bar"],["what":"ever"]]

该如何处理它的任何想法?在 WriteJson ,我再也不能投迈德特因为我不会知道是什么类型的参数,所以一切都只是几乎在这一点上分崩离析。

Any ideas on how to handle it? In WriteJson, I can no longer cast value to MyData because I won't know the type parameters, so everything just pretty much falls apart at that point.

我可以为每个类型组合(让一个单独的类元组LT;双层,双> 和一个元组LT;字符串,双> ...等),但之前,我去蛮力就可以了,我想知道是否有更好的方法。

I could just create separate classes for each type combination (so one for Tuple<double,double> and one for Tuple<string,double> and so on...), but I was wondering if there was a better way before I go brute force on it.

推荐答案

好了,所以这里基本上是我结束做了(如果其他任何人需要类似的东西)。我的收藏看起来是这样的:

Okay, so here's basically what I ended up doing (in case anybody else needs something similar). My collection looks something like this:

    [JsonConverter(typeof(MyDataJsonConverter))]
    public class MyData<S,T> : IList<Tuple<S,T>>
    {
        private List<Tuple<S, T>> _data;
        // all the implementation of IList...
    }

和我的自定义转换器(现在已经不再嵌套在迈德特)看起来是这样的:

And my custom converter (now no longer nested inside MyData) looks like this:

internal class MyDataJsonConverter : JsonConverter
{

    public override bool CanConvert(Type objectType)
    {
        return objectType.IsGenericType && objectType.GetGenericTypeDefinition() == typeof(MyData<,>);
    }

    public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
    {
        // Note: this is strictly for serializing, deserializing is a whole other
        // ball of wax that I don't currently need!
        throw new NotImplementedException();
    }

    public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
    {
        var obj = value as IEnumerable<dynamic>;
        object[][] dataArray = (from dp in obj
                                select new object[] { dp.Item1, dp.Item2 }).ToArray();
        var ser = new JsonSerializer();
        ser.Serialize(writer, dataArray);
    }

    public override bool CanRead
    {
        get
        {
            return false;
        }
    }
}

这篇关于仿制药的JSON序列化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆