| | 1 | | using System.Text.Json; |
| | 2 | | using Spdx3.Exceptions; |
| | 3 | | using Spdx3.Model.Core.Classes; |
| | 4 | | using Spdx3.Utility; |
| | 5 | |
|
| | 6 | | namespace Spdx3.Serialization; |
| | 7 | |
|
| | 8 | | public class Reader |
| | 9 | | { |
| | 10 | | /// <summary> |
| | 11 | | /// The catalog we're writing out |
| | 12 | | /// </summary> |
| | 13 | | private readonly Catalog _catalog; |
| | 14 | |
|
| | 15 | | /// <summary> |
| | 16 | | /// Serialization options |
| | 17 | | /// </summary> |
| 28 | 18 | | private JsonSerializerOptions Options { get; } = new() |
| 7 | 19 | | { |
| 7 | 20 | | WriteIndented = false, |
| 7 | 21 | | MaxDepth = 99 |
| 7 | 22 | | }; |
| | 23 | |
|
| | 24 | | /// <summary> |
| | 25 | | /// Constructor |
| | 26 | | /// </summary> |
| | 27 | | /// <param name="catalog">The catalog of objects to write</param> |
| 7 | 28 | | public Reader(Catalog catalog) |
| | 29 | | { |
| 7 | 30 | | _catalog = catalog; |
| 7 | 31 | | Options.Converters.Add(new SpdxModelConverterFactory()); |
| 7 | 32 | | Options.Converters.Add(new SpdxWrapperConverterFactory()); |
| 7 | 33 | | } |
| | 34 | |
|
| | 35 | | public SpdxDocument ReadFileName(string fileName) |
| | 36 | | { |
| 1 | 37 | | var fileStream = new FileStream(fileName, FileMode.Open); |
| 1 | 38 | | return ReadFileStream(fileStream); |
| | 39 | | } |
| | 40 | |
|
| | 41 | | public SpdxDocument ReadFileStream(FileStream fileStream) |
| | 42 | | { |
| 1 | 43 | | var json = new StreamReader(fileStream).ReadToEnd(); |
| 1 | 44 | | return ReadString(json); |
| | 45 | | } |
| | 46 | |
|
| | 47 | | public SpdxDocument ReadString(string json) |
| | 48 | | { |
| 7 | 49 | | var fileWithWrapper = JsonSerializer.Deserialize<SpdxWrapper>(json, Options); |
| | 50 | |
|
| 2 | 51 | | if (fileWithWrapper == null) |
| | 52 | | { |
| 0 | 53 | | throw new Spdx3SerializationException("Could not deserialize JSON in expected format."); |
| | 54 | | } |
| | 55 | |
|
| 114 | 56 | | foreach (var entry in fileWithWrapper.Graph) |
| | 57 | | { |
| 55 | 58 | | _catalog.Items[entry.SpdxId] = entry; |
| | 59 | | } |
| | 60 | |
|
| 2 | 61 | | return _catalog.GetModel(); |
| | 62 | | } |
| | 63 | | } |