|
| 1 | +using System; |
| 2 | +using System.Collections.Generic; |
| 3 | +using System.IO; |
| 4 | +using Newtonsoft.Json; |
| 5 | + |
| 6 | +namespace OpenEphys.Onix1 |
| 7 | +{ |
| 8 | + internal static class JsonHelper |
| 9 | + { |
| 10 | + public static T DeserializeString<T>(string jsonString) where T : class |
| 11 | + { |
| 12 | + var errors = new List<string>(); |
| 13 | + |
| 14 | + var serializerSettings = new JsonSerializerSettings() |
| 15 | + { |
| 16 | + Error = delegate (object sender, Newtonsoft.Json.Serialization.ErrorEventArgs args) |
| 17 | + { |
| 18 | + errors.Add(args.ErrorContext.Error.Message); |
| 19 | + args.ErrorContext.Handled = true; |
| 20 | + } |
| 21 | + }; |
| 22 | + |
| 23 | + try |
| 24 | + { |
| 25 | + var obj = JsonConvert.DeserializeObject<T>(jsonString, serializerSettings); |
| 26 | + |
| 27 | + if (errors.Count > 0) |
| 28 | + { |
| 29 | + Console.WriteLine("There were errors encountered while parsing a JSON string.\n"); |
| 30 | + foreach (var e in errors) |
| 31 | + { |
| 32 | + Console.Error.WriteLine(e); |
| 33 | + } |
| 34 | + return null; |
| 35 | + } |
| 36 | + |
| 37 | + return obj; |
| 38 | + } |
| 39 | + catch (JsonReaderException e) |
| 40 | + { |
| 41 | + throw new InvalidDataException("Invalid JSON format", e); |
| 42 | + } |
| 43 | + catch (JsonSerializationException e) |
| 44 | + { |
| 45 | + throw new InvalidDataException("Failed to deserialize JSON", e); |
| 46 | + } |
| 47 | + } |
| 48 | + |
| 49 | + public static void SerializeObject(object obj, string filepath) |
| 50 | + { |
| 51 | + if (string.IsNullOrEmpty(filepath)) |
| 52 | + return; |
| 53 | + |
| 54 | + var serializerSettings = new JsonSerializerSettings() |
| 55 | + { |
| 56 | + NullValueHandling = NullValueHandling.Ignore, |
| 57 | + }; |
| 58 | + |
| 59 | + var stringJson = JsonConvert.SerializeObject(obj, Formatting.Indented, serializerSettings); |
| 60 | + |
| 61 | + try |
| 62 | + { |
| 63 | + File.WriteAllText(filepath, stringJson); |
| 64 | + } |
| 65 | + catch (UnauthorizedAccessException e) |
| 66 | + { |
| 67 | + throw new IOException($"Access denied writing to '{filepath}'. Check file permissions.", e); |
| 68 | + } |
| 69 | + catch (DirectoryNotFoundException e) |
| 70 | + { |
| 71 | + throw new IOException($"Directory not found for '{filepath}'. Ensure the directory exists.", e); |
| 72 | + } |
| 73 | + catch (PathTooLongException e) |
| 74 | + { |
| 75 | + throw new IOException($"File path '{filepath}' exceeds system maximum length.", e); |
| 76 | + } |
| 77 | + catch (IOException e) |
| 78 | + { |
| 79 | + throw new IOException($"Unable to write to '{filepath}'. The file may be in use.", e); |
| 80 | + } |
| 81 | + catch (Exception e) |
| 82 | + { |
| 83 | + throw new IOException($"Unexpected error writing to '{filepath}'.", e); |
| 84 | + } |
| 85 | + } |
| 86 | + } |
| 87 | +} |
0 commit comments