benjaminvr

BronParser

Dec 27th, 2021
229
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 4.36 KB | None | 0 0
  1.     public class BronParserException : Exception {
  2.         public BronParserException(string message) : base(message) {
  3.         }
  4.  
  5.         public BronParserException(string message, Exception innerException) : base(message, innerException) {
  6.         }
  7.     }  
  8.  
  9. public static class BronParser {
  10.     public static object MaakNestedDictionaryVanJObject(object reqObj) {
  11.             switch (reqObj) {
  12.                 case JObject jObject:
  13.                     return (
  14.                         (IEnumerable<KeyValuePair<string, JToken>>)jObject)
  15.                         .ToDictionary(j => j.Key, j => MaakNestedDictionaryVanJObject(j.Value)
  16.                     );
  17.                 case JArray jArray:
  18.                     return jArray.Select(MaakNestedDictionaryVanJObject).ToList();
  19.                 case JValue jValue:
  20.                     return jValue.Value;
  21.                 default:
  22.                     throw new BronParserException($"Dit type kan niet geparsed worden: {reqObj.GetType()}");
  23.             }
  24.         }
  25.    
  26.     public static T ParseCast<T>(object data, JSchema ValidatieSchema=null, bool toJsonFilterNulls=true) {
  27.  
  28.             var JSS = new JsonSerializer {
  29.                 NullValueHandling = NullValueHandling.Ignore,
  30.                 ReferenceLoopHandling = ReferenceLoopHandling.Ignore // https://dotnetfiddle.net/frCSa3
  31.             };
  32.  
  33.             JObject parsed_as_json = null;
  34.             JObject parsed_as_obj = null;
  35.  
  36.             try {
  37.                 if (data.GetType() == typeof(string))
  38.                     { parsed_as_json = JObject.Parse((string)data);
  39.                 }
  40.             } catch(JsonReaderException) { }
  41.  
  42.             try {
  43.                 parsed_as_obj = JObject.FromObject(data, JSS);
  44.             } catch (ArgumentException e) when (e.Message.Contains("JObject instance expected")) { }
  45.            
  46.             JObject parseResultaat = parsed_as_json is not null
  47.                                      ? parsed_as_json
  48.                                      : parsed_as_obj is not null
  49.                                          ? parsed_as_obj
  50.                                          : throw new BronParserException(
  51.                                             "Kon de data niet parsen. " +
  52.                                             "Indien je een JSON string wenst te parsen, " +
  53.                                             "controleer of je JSON valid is."
  54.                                            );
  55.  
  56.             if (ValidatieSchema is not null) {
  57.                 if (!parseResultaat.IsValid(ValidatieSchema)) {
  58.                     throw new BronParserException(
  59.                         "Het JSON object voldoet niet aan de voorwaarden " +
  60.                         "opgelegd in het meegegeven schema."
  61.                     );
  62.                 }
  63.             }
  64.  
  65.             /**Optie 1 - omzetten naar json string**/
  66.             if (typeof(T) == typeof(string)) {                                          
  67.                 string filteredResultaat;
  68.  
  69.                 if (toJsonFilterNulls) {
  70.                     // Omweg (from+to) vereist aangezien anders nulls niet genegeerd worden
  71.                     // (komt door JTokenType.Null)
  72.                     // https://stackoverflow.com/questions/33027409/json-net-serialize-jobject-while-ignoring-null-properties
  73.                     filteredResultaat = JObject.FromObject(
  74.                                             parseResultaat.ToObject(typeof(object)),
  75.                                             JSS
  76.                                         ).ToString();
  77.                 } else {
  78.                     filteredResultaat = parseResultaat.ToString();
  79.                 }
  80.  
  81.                 return (T)Convert.ChangeType(filteredResultaat, typeof(T));
  82.  
  83.             /**Optie 2 - specifiek omzetten naar een object met type T **/
  84.             } else if ((typeof(T) == typeof(JObject) || typeof(T).GetType().IsClass)
  85.                         && typeof(T) != typeof(object)) {            // https://dotnetfiddle.net/puxB1a
  86.                 return (T)parseResultaat.ToObject(typeof(T));
  87.  
  88.             /**Optie 3 - generiek omzetten naar een "object" **/
  89.             } else {                                                                    
  90.                 return (T)parseResultaat.ToObject(typeof(object));
  91.             }
  92.  
  93.             throw new BronParserException("Kon de data niet parsen.");
  94.         }
  95.  
  96.  
  97. }
Advertisement
Add Comment
Please, Sign In to add comment