| | 1 | | using System.Collections; |
| | 2 | | using System.Diagnostics; |
| | 3 | | using System.Reflection; |
| | 4 | | using System.Text.Json; |
| | 5 | | using System.Text.Json.Serialization; |
| | 6 | | using Spdx3.Exceptions; |
| | 7 | | using Spdx3.Model; |
| | 8 | | using Spdx3.Utility; |
| | 9 | | using Uri = System.Uri; |
| | 10 | |
|
| | 11 | | namespace Spdx3.Serialization; |
| | 12 | |
|
| | 13 | | public class SpdxModelConverter<T> : JsonConverter<T> |
| | 14 | | { |
| | 15 | | /// <summary> |
| | 16 | | /// The main Read method implementation for this implementation of a JsonConverter |
| | 17 | | /// </summary> |
| | 18 | | /// <param name="reader">The JSON reader</param> |
| | 19 | | /// <param name="typeToConvert">The type we're trying/expecting to construct from the JSON</param> |
| | 20 | | /// <param name="options">Options for the converter</param> |
| | 21 | | /// <returns>The constructed instance read from the JSON</returns> |
| | 22 | | /// <exception cref="Spdx3SerializationException">If something specific to SPDX3 goes wrong</exception> |
| | 23 | | public override T Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) |
| | 24 | | { |
| 28 | 25 | | var result = (T?)Activator.CreateInstance(typeToConvert, true) ?? |
| 28 | 26 | | throw new Spdx3SerializationException($"Could not create instance of {typeToConvert}"); |
| | 27 | |
|
| | 28 | | // Initialize to some throwaway non-null value |
| 28 | 29 | | var currentProperty = result.GetType().GetProperties().First(); |
| | 30 | |
|
| 229 | 31 | | while (reader.Read()) |
| | 32 | | { |
| 205 | 33 | | switch (reader.TokenType) |
| | 34 | | { |
| | 35 | | case JsonTokenType.PropertyName: |
| 84 | 36 | | var newPropName = reader.GetString() ?? |
| 84 | 37 | | throw new Spdx3SerializationException("Couldn't read property name"); |
| 84 | 38 | | currentProperty = GetPropertyFromJsonElementName(typeToConvert, newPropName); |
| 84 | 39 | | break; |
| | 40 | |
|
| | 41 | | case JsonTokenType.String: |
| 75 | 42 | | LoadJsonStringIntoProperty(result, currentProperty, |
| 75 | 43 | | reader.GetString() ?? throw new Spdx3SerializationException("Couldn't read string")); |
| | 44 | |
|
| 75 | 45 | | break; |
| | 46 | | case JsonTokenType.Number: |
| 14 | 47 | | if (currentProperty.PropertyType == typeof(int)) |
| | 48 | | { |
| 1 | 49 | | currentProperty.SetValue(result, reader.GetInt32()); |
| | 50 | | } |
| | 51 | | else |
| | 52 | | { |
| 13 | 53 | | currentProperty.SetValue(result, reader.GetDouble()); |
| | 54 | | } |
| | 55 | |
|
| | 56 | | break; |
| | 57 | | } |
| | 58 | | } |
| | 59 | |
|
| 24 | 60 | | return result; |
| | 61 | | } |
| | 62 | |
|
| | 63 | | /// <summary> |
| | 64 | | /// Take a given string value just read from the JSON, and load its value into whatever the property is that we' |
| | 65 | | /// currently reading. |
| | 66 | | /// </summary> |
| | 67 | | /// <param name="result">The object with the property</param> |
| | 68 | | /// <param name="currentProperty">The property of the object that we're loading into</param> |
| | 69 | | /// <param name="strVal">The string value</param> |
| | 70 | | /// <exception cref="Spdx3SerializationException">If something specific to SPDX3 goes wrong</exception> |
| | 71 | | private static void LoadJsonStringIntoProperty(object result, PropertyInfo currentProperty, string strVal) |
| | 72 | | { |
| | 73 | | Debug.Assert(currentProperty != null, $"There is no current property to receive for value {strVal}"); |
| | 74 | |
|
| 75 | 75 | | if (currentProperty.PropertyType == typeof(string)) |
| | 76 | | { |
| 24 | 77 | | currentProperty.SetValue(result, strVal); |
| | 78 | | } |
| 51 | 79 | | else if (currentProperty.PropertyType == typeof(Uri)) |
| | 80 | | { |
| 19 | 81 | | currentProperty.SetValue(result, new Uri(strVal)); |
| | 82 | | } |
| 32 | 83 | | else if (currentProperty.PropertyType == typeof(DateTimeOffset)) |
| | 84 | | { |
| 1 | 85 | | currentProperty.SetValue(result, DateTimeOffset.Parse(strVal)); |
| | 86 | | } |
| 31 | 87 | | else if (currentProperty.PropertyType.IsEnum) |
| | 88 | | { |
| 3 | 89 | | currentProperty.SetValue(result, Enum.Parse(currentProperty.PropertyType, strVal)); |
| | 90 | | } |
| 28 | 91 | | else if (currentProperty.PropertyType.IsGenericType) |
| | 92 | | { |
| 14 | 93 | | LoadJsonStringIntoGenericProperty(result, currentProperty, strVal); |
| | 94 | | } |
| 14 | 95 | | else if (currentProperty.PropertyType.IsSubclassOf(typeof(BaseModelClass))) |
| | 96 | | { |
| | 97 | | /* |
| | 98 | | * At this point we have a string that is the URN of another Element, which we may or may not |
| | 99 | | * have read yet. For now, make a placeholder element of the type needed and the ID in the json. |
| | 100 | | * Later, we're going to need to go through the objects and replace the placeholder with the real one. |
| | 101 | | */ |
| 14 | 102 | | var placeHolder = Convert.ChangeType(Activator.CreateInstance(currentProperty.PropertyType, true), |
| 14 | 103 | | currentProperty.PropertyType); |
| | 104 | |
|
| | 105 | | #pragma warning disable CS8602 // Dereference of a possibly null reference. |
| 14 | 106 | | currentProperty.PropertyType.GetProperty("SpdxId").SetValue(placeHolder, new Uri(strVal)); |
| 14 | 107 | | currentProperty.PropertyType.GetProperty("Type").SetValue(placeHolder, |
| 14 | 108 | | #pragma warning restore CS8602 // Dereference of a possibly null reference. |
| 14 | 109 | | Naming.SpdxTypeForClass(currentProperty.PropertyType)); |
| 14 | 110 | | currentProperty.SetValue(result, placeHolder); |
| | 111 | | } |
| | 112 | | else |
| | 113 | | { |
| 0 | 114 | | throw new Spdx3SerializationException($"No string handler for a {currentProperty.PropertyType.Name}"); |
| | 115 | | } |
| | 116 | | } |
| | 117 | |
|
| | 118 | | private static void LoadJsonStringIntoGenericProperty(object result, PropertyInfo currentProperty, string strVal) |
| | 119 | | { |
| 14 | 120 | | var genericType = currentProperty.PropertyType.GetGenericArguments()[0]; |
| | 121 | |
|
| 14 | 122 | | if (genericType.IsEnum && currentProperty.GetValue(result) is IList enumList) |
| | 123 | | { |
| 2 | 124 | | enumList.Add(Enum.Parse(genericType, strVal)); |
| | 125 | | } |
| 12 | 126 | | else if (genericType.IsEnum) |
| | 127 | | { |
| 3 | 128 | | currentProperty.SetValue(result, Enum.Parse(genericType, strVal)); |
| | 129 | | } |
| 9 | 130 | | else if (genericType == typeof(bool)) |
| | 131 | | { |
| 1 | 132 | | currentProperty.SetValue(result, bool.Parse(strVal)); |
| | 133 | | } |
| 8 | 134 | | else if (genericType == typeof(string) && currentProperty.GetValue(result) is IList strList) |
| | 135 | | { |
| 2 | 136 | | strList.Add(strVal); |
| | 137 | | } |
| 6 | 138 | | else if (genericType == typeof(DateTimeOffset) && currentProperty.GetValue(result) is IList dateTimeOffsetList) |
| | 139 | | { |
| 3 | 140 | | dateTimeOffsetList.Add(DateTimeOffset.Parse(strVal)); |
| | 141 | | } |
| 3 | 142 | | else if (genericType == typeof(DateTimeOffset)) |
| | 143 | | { |
| 1 | 144 | | currentProperty.SetValue(result, DateTimeOffset.Parse(strVal)); |
| | 145 | | } |
| 2 | 146 | | else if (genericType.IsAssignableTo(typeof(BaseModelClass))) |
| | 147 | | { |
| | 148 | | /* |
| | 149 | | * At this point we have a string that is the URN of another Element, which we may or may not |
| | 150 | | * have read yet. For now, make a placeholder element of the type needed and the ID in the json. |
| | 151 | | * Later, we're going to need to go through the objects and replace the placeholder with the real one. |
| | 152 | | */ |
| 2 | 153 | | var placeHolder = Convert.ChangeType(Activator.CreateInstance(genericType, true), genericType) ?? |
| 2 | 154 | | throw new Spdx3SerializationException($"Could not create instance of {genericType}"); |
| 2 | 155 | | var type = placeHolder.GetType(); |
| 2 | 156 | | var spdxIdProperty = type.GetProperty("SpdxId") ?? |
| 2 | 157 | | throw new Spdx3SerializationException("Could not get spdxId property"); |
| 2 | 158 | | spdxIdProperty.SetValue(placeHolder, new Uri(strVal)); |
| | 159 | |
|
| 2 | 160 | | var typeProperty = type.GetProperty("Type") ?? |
| 2 | 161 | | throw new Spdx3SerializationException("Could not get type property"); |
| 2 | 162 | | typeProperty.SetValue(placeHolder, Naming.SpdxTypeForClass(genericType)); |
| | 163 | |
|
| | 164 | | #pragma warning disable CS8602 // Dereference of a possibly null reference. |
| 2 | 165 | | (currentProperty.GetValue(result) as IList).Add(placeHolder); |
| | 166 | | #pragma warning restore CS8602 // Dereference of a possibly null reference. |
| | 167 | | } |
| | 168 | | else |
| | 169 | | { |
| 0 | 170 | | throw new Spdx3SerializationException($"The type {genericType} is not supported"); |
| | 171 | | } |
| | 172 | | } |
| | 173 | |
|
| | 174 | | /// <summary> |
| | 175 | | /// The main Write operation for this implementation of the JsonConverter |
| | 176 | | /// </summary> |
| | 177 | | /// <param name="writer">The writer we are writing to</param> |
| | 178 | | /// <param name="value">The value we're writing</param> |
| | 179 | | /// <param name="options">The options for the JsonSerializer</param> |
| | 180 | | public override void Write(Utf8JsonWriter writer, T value, JsonSerializerOptions options) |
| | 181 | | { |
| 139 | 182 | | if (value == null) |
| | 183 | | { |
| 0 | 184 | | return; |
| | 185 | | } |
| | 186 | |
|
| 139 | 187 | | var props = value.GetType().GetProperties() |
| 2425 | 188 | | .Where(prop => Attribute.IsDefined(prop, typeof(JsonPropertyNameAttribute))); |
| | 189 | |
|
| 139 | 190 | | writer.WriteStartObject(); |
| | 191 | |
|
| 5485 | 192 | | foreach (var prop in props.Where(prop => prop.GetValue(value) != null)) |
| | 193 | | { |
| 1530 | 194 | | var jsonElementName = GetJsonElementNameFromPropertyAttribute(prop); |
| | 195 | |
|
| 1530 | 196 | | var propType = prop.PropertyType; |
| 1530 | 197 | | var propVal = prop.GetValue(value); |
| | 198 | |
|
| | 199 | | // If it's a list of OTHER SpdxClasses, don't serialize the objects, just serialize an array of references |
| 1530 | 200 | | if (propType.IsGenericType) |
| | 201 | | { |
| 750 | 202 | | if (propType.GenericTypeArguments[0].IsSubclassOf(typeof(BaseModelClass)) && |
| 750 | 203 | | propVal is IList spdxClasses) |
| | 204 | | { |
| 570 | 205 | | if (spdxClasses.Count > 0) |
| | 206 | | { |
| 212 | 207 | | WriteReferencesToListItems(writer, spdxClasses, jsonElementName); |
| | 208 | | } |
| | 209 | |
|
| 212 | 210 | | continue; |
| | 211 | | } |
| | 212 | |
|
| | 213 | | // If it's a list of Enum values, serialize the names of the values |
| 180 | 214 | | if (propType.GenericTypeArguments[0].IsEnum && propVal is IList enums) |
| | 215 | | { |
| 43 | 216 | | if (enums.Count > 0) |
| | 217 | | { |
| 14 | 218 | | WriteReferencesToEnumValues(writer, propType.GenericTypeArguments[0], enums, jsonElementName); |
| | 219 | | } |
| | 220 | |
|
| 14 | 221 | | continue; |
| | 222 | | } |
| | 223 | | } |
| | 224 | |
|
| 917 | 225 | | WriteSimpleProperty(writer, propVal, jsonElementName); |
| | 226 | | } |
| | 227 | |
|
| 139 | 228 | | writer.WriteEndObject(); |
| 139 | 229 | | } |
| | 230 | |
|
| | 231 | | private static void WriteSimpleProperty(Utf8JsonWriter writer, object? propVal, string jsonElementName) |
| | 232 | | { |
| | 233 | | switch (propVal) |
| | 234 | | { |
| | 235 | | case Enum: |
| 57 | 236 | | writer.WriteString(jsonElementName, Enum.GetName(propVal.GetType(), propVal)); |
| 57 | 237 | | break; |
| | 238 | | case int val: |
| 2 | 239 | | writer.WriteNumber(jsonElementName, val); |
| 2 | 240 | | break; |
| | 241 | | case double val: |
| 11 | 242 | | writer.WriteNumber(jsonElementName, val); |
| 11 | 243 | | break; |
| | 244 | | case bool val: |
| 11 | 245 | | writer.WriteBoolean(jsonElementName, val); |
| 11 | 246 | | break; |
| | 247 | | case Uri val: |
| 148 | 248 | | writer.WriteString(jsonElementName, val.ToString()); |
| 148 | 249 | | break; |
| | 250 | | case DateTimeOffset val: |
| 66 | 251 | | writer.WriteString(jsonElementName, val.UtcDateTime.ToString("yyyy-MM-ddTHH:mm:ssZ")); |
| 66 | 252 | | break; |
| | 253 | | case string val: |
| 404 | 254 | | writer.WriteString(jsonElementName, val); |
| 404 | 255 | | break; |
| | 256 | | case BaseModelClass: |
| 172 | 257 | | writer.WriteString(jsonElementName, (string)(propVal as dynamic).SpdxId.ToString()); |
| 172 | 258 | | break; |
| | 259 | | case List<string> list: |
| 30 | 260 | | if (list.Count > 0) |
| | 261 | | { |
| 9 | 262 | | writer.WritePropertyName(jsonElementName); |
| 9 | 263 | | writer.WriteStartArray(); |
| 9 | 264 | | list.ForEach(writer.WriteStringValue); |
| 9 | 265 | | writer.WriteEndArray(); |
| | 266 | | } |
| | 267 | |
|
| 9 | 268 | | break; |
| | 269 | | case List<Uri> list: |
| 16 | 270 | | if (list.Count > 0) |
| | 271 | | { |
| 5 | 272 | | writer.WritePropertyName(jsonElementName); |
| 5 | 273 | | writer.WriteStartArray(); |
| 13 | 274 | | list.ForEach(u => writer.WriteStringValue(u.ToString())); |
| 5 | 275 | | writer.WriteEndArray(); |
| | 276 | | } |
| | 277 | |
|
| 5 | 278 | | break; |
| | 279 | | default: |
| 0 | 280 | | throw new Spdx3Exception($"Unhandled class type {propVal?.GetType().FullName}"); |
| | 281 | | } |
| 32 | 282 | | } |
| | 283 | |
|
| | 284 | | private static void WriteReferencesToListItems(Utf8JsonWriter writer, IList spdxClasses, string jsonElementName) |
| | 285 | | { |
| 212 | 286 | | writer.WritePropertyName(jsonElementName); |
| 212 | 287 | | writer.WriteStartArray(); |
| | 288 | |
|
| 876 | 289 | | foreach (var spdxClass in spdxClasses) |
| | 290 | | { |
| 226 | 291 | | if (spdxClass != null) |
| | 292 | | { |
| | 293 | | #pragma warning disable CS8602 // Dereference of a possibly null reference. |
| 226 | 294 | | writer.WriteStringValue((spdxClass as BaseModelClass).SpdxId.ToString()); |
| | 295 | | #pragma warning restore CS8602 // Dereference of a possibly null reference. |
| | 296 | | } |
| | 297 | | } |
| | 298 | |
|
| 212 | 299 | | writer.WriteEndArray(); |
| 212 | 300 | | } |
| | 301 | |
|
| | 302 | | private static void WriteReferencesToEnumValues(Utf8JsonWriter writer, Type enumType, IList enumValues, |
| | 303 | | string jsonElementName) |
| | 304 | | { |
| 14 | 305 | | writer.WritePropertyName(jsonElementName); |
| 14 | 306 | | writer.WriteStartArray(); |
| | 307 | |
|
| 70 | 308 | | foreach (var enumValue in enumValues) |
| | 309 | | { |
| 21 | 310 | | if (enumValue != null) |
| | 311 | | { |
| 21 | 312 | | writer.WriteStringValue(Enum.GetName(enumType, enumValue)); |
| | 313 | | } |
| | 314 | | } |
| | 315 | |
|
| 14 | 316 | | writer.WriteEndArray(); |
| 14 | 317 | | } |
| | 318 | |
|
| | 319 | |
|
| | 320 | | private static string GetJsonElementNameFromPropertyAttribute(PropertyInfo prop) |
| | 321 | | { |
| 1530 | 322 | | var jsonElementName = ""; |
| | 323 | |
|
| 10710 | 324 | | foreach (var propAttr in prop.GetCustomAttributes()) |
| | 325 | | { |
| 3825 | 326 | | if (propAttr is JsonPropertyNameAttribute) |
| | 327 | | { |
| 1530 | 328 | | jsonElementName = (propAttr as dynamic).Name; |
| | 329 | | } |
| | 330 | | } |
| | 331 | |
|
| 1530 | 332 | | return jsonElementName; |
| | 333 | | } |
| | 334 | |
|
| | 335 | |
|
| | 336 | | private static PropertyInfo GetPropertyFromJsonElementName(Type typeToConvert, string elementName) |
| | 337 | | { |
| 1974 | 338 | | foreach (var prop in typeToConvert.GetProperties()) |
| | 339 | | { |
| 6284 | 340 | | foreach (var propAttr in prop.GetCustomAttributes()) |
| | 341 | | { |
| 2239 | 342 | | if (propAttr is JsonPropertyNameAttribute && elementName == (propAttr as dynamic).Name) |
| | 343 | | { |
| 84 | 344 | | return prop; |
| | 345 | | } |
| | 346 | | } |
| | 347 | | } |
| | 348 | |
|
| 0 | 349 | | throw new Spdx3SerializationException( |
| 0 | 350 | | $"Unable to get property on {typeToConvert.Name} for JSON element named {elementName}"); |
| 84 | 351 | | } |
| | 352 | | } |