tangxu
2024-10-22 6a07c4c846ffbb1e93afdf0260e123e4c145f419
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
using System;
using System.Collections;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Reflection;
using DPumpHydr.WinFrmUI.WenSkin.Json.Linq;
using DPumpHydr.WinFrmUI.WenSkin.Json.Serialization;
using DPumpHydr.WinFrmUI.WenSkin.Json.Utilities;
 
namespace DPumpHydr.WinFrmUI.WenSkin.Json.Converters
{
    /// <summary>
    /// Converts a F# discriminated union type to and from JSON.
    /// </summary>
    public class DiscriminatedUnionConverter : JsonConverter
    {
        internal class Union
        {
            public List<UnionCase> Cases;
 
            public FSharpFunction TagReader { get; set; }
        }
 
        internal class UnionCase
        {
            public int Tag;
 
            public string Name;
 
            public PropertyInfo[] Fields;
 
            public FSharpFunction FieldReader;
 
            public FSharpFunction Constructor;
        }
 
        private const string CasePropertyName = "Case";
 
        private const string FieldsPropertyName = "Fields";
 
        private static readonly ThreadSafeStore<Type, Union> UnionCache = new ThreadSafeStore<Type, Union>(CreateUnion);
 
        private static readonly ThreadSafeStore<Type, Type> UnionTypeLookupCache = new ThreadSafeStore<Type, Type>(CreateUnionTypeLookup);
 
        private static Type CreateUnionTypeLookup(Type t)
        {
            object arg = ((object[])FSharpUtils.GetUnionCases(null, t, null)).First();
            return (Type)FSharpUtils.GetUnionCaseInfoDeclaringType(arg);
        }
 
        private static Union CreateUnion(Type t)
        {
            Union union = new Union();
            union.TagReader = (FSharpFunction)FSharpUtils.PreComputeUnionTagReader(null, t, null);
            union.Cases = new List<UnionCase>();
            object[] array = (object[])FSharpUtils.GetUnionCases(null, t, null);
            foreach (object obj in array)
            {
                UnionCase unionCase = new UnionCase();
                unionCase.Tag = (int)FSharpUtils.GetUnionCaseInfoTag(obj);
                unionCase.Name = (string)FSharpUtils.GetUnionCaseInfoName(obj);
                unionCase.Fields = (PropertyInfo[])FSharpUtils.GetUnionCaseInfoFields(obj);
                unionCase.FieldReader = (FSharpFunction)FSharpUtils.PreComputeUnionReader(null, obj, null);
                unionCase.Constructor = (FSharpFunction)FSharpUtils.PreComputeUnionConstructor(null, obj, null);
                union.Cases.Add(unionCase);
            }
            return union;
        }
 
        /// <summary>
        /// Writes the JSON representation of the object.
        /// </summary>
        /// <param name="writer">The <see cref="T:Newtonsoft.Json.JsonWriter" /> to write to.</param>
        /// <param name="value">The value.</param>
        /// <param name="serializer">The calling serializer.</param>
        public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
        {
            DefaultContractResolver defaultContractResolver = serializer.ContractResolver as DefaultContractResolver;
            Type key = UnionTypeLookupCache.Get(value.GetType());
            Union union = UnionCache.Get(key);
            int tag = (int)union.TagReader.Invoke(value);
            UnionCase unionCase = union.Cases.Single((UnionCase c) => c.Tag == tag);
            writer.WriteStartObject();
            writer.WritePropertyName((defaultContractResolver != null) ? defaultContractResolver.GetResolvedPropertyName("Case") : "Case");
            writer.WriteValue(unionCase.Name);
            if (unionCase.Fields != null && unionCase.Fields.Length != 0)
            {
                object[] obj = (object[])unionCase.FieldReader.Invoke(value);
                writer.WritePropertyName((defaultContractResolver != null) ? defaultContractResolver.GetResolvedPropertyName("Fields") : "Fields");
                writer.WriteStartArray();
                object[] array = obj;
                foreach (object value2 in array)
                {
                    serializer.Serialize(writer, value2);
                }
                writer.WriteEndArray();
            }
            writer.WriteEndObject();
        }
 
        /// <summary>
        /// Reads the JSON representation of the object.
        /// </summary>
        /// <param name="reader">The <see cref="T:Newtonsoft.Json.JsonReader" /> to read from.</param>
        /// <param name="objectType">Type of the object.</param>
        /// <param name="existingValue">The existing value of object being read.</param>
        /// <param name="serializer">The calling serializer.</param>
        /// <returns>The object value.</returns>
        public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
        {
            if (reader.TokenType == JsonToken.Null)
            {
                return null;
            }
            UnionCase unionCase = null;
            string caseName = null;
            JArray jArray = null;
            reader.ReadAndAssert();
            while (reader.TokenType == JsonToken.PropertyName)
            {
                string text = reader.Value.ToString();
                if (string.Equals(text, "Case", StringComparison.OrdinalIgnoreCase))
                {
                    reader.ReadAndAssert();
                    Union union = UnionCache.Get(objectType);
                    caseName = reader.Value.ToString();
                    unionCase = union.Cases.SingleOrDefault((UnionCase c) => c.Name == caseName);
                    if (unionCase == null)
                    {
                        throw JsonSerializationException.Create(reader, "No union type found with the name '{0}'.".FormatWith(CultureInfo.InvariantCulture, caseName));
                    }
                }
                else
                {
                    if (!string.Equals(text, "Fields", StringComparison.OrdinalIgnoreCase))
                    {
                        throw JsonSerializationException.Create(reader, "Unexpected property '{0}' found when reading union.".FormatWith(CultureInfo.InvariantCulture, text));
                    }
                    reader.ReadAndAssert();
                    if (reader.TokenType != JsonToken.StartArray)
                    {
                        throw JsonSerializationException.Create(reader, "Union fields must been an array.");
                    }
                    jArray = (JArray)JToken.ReadFrom(reader);
                }
                reader.ReadAndAssert();
            }
            if (unionCase == null)
            {
                throw JsonSerializationException.Create(reader, "No '{0}' property with union name found.".FormatWith(CultureInfo.InvariantCulture, "Case"));
            }
            object[] array = new object[unionCase.Fields.Length];
            if (unionCase.Fields.Length != 0 && jArray == null)
            {
                throw JsonSerializationException.Create(reader, "No '{0}' property with union fields found.".FormatWith(CultureInfo.InvariantCulture, "Fields"));
            }
            if (jArray != null)
            {
                if (unionCase.Fields.Length != jArray.Count)
                {
                    throw JsonSerializationException.Create(reader, "The number of field values does not match the number of properties defined by union '{0}'.".FormatWith(CultureInfo.InvariantCulture, caseName));
                }
                for (int i = 0; i < jArray.Count; i++)
                {
                    JToken jToken = jArray[i];
                    PropertyInfo propertyInfo = unionCase.Fields[i];
                    array[i] = jToken.ToObject(propertyInfo.PropertyType, serializer);
                }
            }
            object[] args = new object[1] { array };
            return unionCase.Constructor.Invoke(args);
        }
 
        /// <summary>
        /// Determines whether this instance can convert the specified object type.
        /// </summary>
        /// <param name="objectType">Type of the object.</param>
        /// <returns>
        ///     <c>true</c> if this instance can convert the specified object type; otherwise, <c>false</c>.
        /// </returns>
        public override bool CanConvert(Type objectType)
        {
            if (typeof(IEnumerable).IsAssignableFrom(objectType))
            {
                return false;
            }
            object[] customAttributes = objectType.GetCustomAttributes(inherit: true);
            bool flag = false;
            object[] array = customAttributes;
            for (int i = 0; i < array.Length; i++)
            {
                Type type = array[i].GetType();
                if (type.FullName == "Microsoft.FSharp.Core.CompilationMappingAttribute")
                {
                    FSharpUtils.EnsureInitialized(type.Assembly());
                    flag = true;
                    break;
                }
            }
            if (!flag)
            {
                return false;
            }
            return (bool)FSharpUtils.IsUnion(null, objectType, null);
        }
    }
}