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
using System;
using System.Collections.Generic;
using System.Data.SqlTypes;
using System.Globalization;
using DPumpHydr.WinFrmUI.WenSkin.Json.Utilities;
 
namespace DPumpHydr.WinFrmUI.WenSkin.Json.Converters
{
    /// <summary>
    /// Converts a binary value to and from a base 64 string value.
    /// </summary>
    public class BinaryConverter : JsonConverter
    {
        private const string BinaryTypeName = "System.Data.Linq.Binary";
 
        private const string BinaryToArrayName = "ToArray";
 
        private ReflectionObject _reflectionObject;
 
        /// <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)
        {
            if (value == null)
            {
                writer.WriteNull();
                return;
            }
            byte[] byteArray = GetByteArray(value);
            writer.WriteValue(byteArray);
        }
 
        private byte[] GetByteArray(object value)
        {
            if (value.GetType().AssignableToTypeName("System.Data.Linq.Binary"))
            {
                EnsureReflectionObject(value.GetType());
                return (byte[])_reflectionObject.GetValue(value, "ToArray");
            }
            if (value is SqlBinary)
            {
                return ((SqlBinary)value).Value;
            }
            throw new JsonSerializationException("Unexpected value type when writing binary: {0}".FormatWith(CultureInfo.InvariantCulture, value.GetType()));
        }
 
        private void EnsureReflectionObject(Type t)
        {
            if (_reflectionObject == null)
            {
                _reflectionObject = ReflectionObject.Create(t, t.GetConstructor(new Type[1] { typeof(byte[]) }), "ToArray");
            }
        }
 
        /// <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)
            {
                if (!ReflectionUtils.IsNullable(objectType))
                {
                    throw JsonSerializationException.Create(reader, "Cannot convert null value to {0}.".FormatWith(CultureInfo.InvariantCulture, objectType));
                }
                return null;
            }
            byte[] array;
            if (reader.TokenType == JsonToken.StartArray)
            {
                array = ReadByteArray(reader);
            }
            else
            {
                if (reader.TokenType != JsonToken.String)
                {
                    throw JsonSerializationException.Create(reader, "Unexpected token parsing binary. Expected String or StartArray, got {0}.".FormatWith(CultureInfo.InvariantCulture, reader.TokenType));
                }
                array = Convert.FromBase64String(reader.Value.ToString());
            }
            Type type = (ReflectionUtils.IsNullableType(objectType) ? Nullable.GetUnderlyingType(objectType) : objectType);
            if (type.AssignableToTypeName("System.Data.Linq.Binary"))
            {
                EnsureReflectionObject(type);
                return _reflectionObject.Creator(array);
            }
            if (type == typeof(SqlBinary))
            {
                return new SqlBinary(array);
            }
            throw JsonSerializationException.Create(reader, "Unexpected object type when writing binary: {0}".FormatWith(CultureInfo.InvariantCulture, objectType));
        }
 
        private byte[] ReadByteArray(JsonReader reader)
        {
            List<byte> list = new List<byte>();
            while (reader.Read())
            {
                switch (reader.TokenType)
                {
                case JsonToken.Integer:
                    list.Add(Convert.ToByte(reader.Value, CultureInfo.InvariantCulture));
                    break;
                case JsonToken.EndArray:
                    return list.ToArray();
                default:
                    throw JsonSerializationException.Create(reader, "Unexpected token when reading bytes: {0}".FormatWith(CultureInfo.InvariantCulture, reader.TokenType));
                case JsonToken.Comment:
                    break;
                }
            }
            throw JsonSerializationException.Create(reader, "Unexpected end when reading bytes.");
        }
 
        /// <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 (objectType.AssignableToTypeName("System.Data.Linq.Binary"))
            {
                return true;
            }
            if (objectType == typeof(SqlBinary) || objectType == typeof(SqlBinary?))
            {
                return true;
            }
            return false;
        }
    }
}