/// <summary> /// Enumerate the top-level entities in a JSON array. /// </summary> public IEnumerable <PersistEntity> ArrayEntities(string jsonArray, Persistence persist) { JArray entities = JArray.Parse(jsonArray); foreach (var child in entities.Children()) { var entity = new PersistEntity(); entity.Json = LessPretty(child.ToString()); // Read top-level attributes to find variable values foreach (var attrib in child.Children()) { JProperty prop = attrib as JProperty; if (persist.OutputVars.Contains(prop.Name)) { string value = prop.Value.ToString(Formatting.None); if (value.Length > 1 && value[0] == '"' && value[value.Length - 1] == '"') { entity.PersistValues.Add(prop.Name, value.Substring(1, value.Length - 2)); } else { entity.PersistValues.Add(prop.Name, value); } } } yield return(entity); } }
/// <summary> /// Like the ArrayEntities method but for a single object /// rather than an array of objects. /// /// </summary> public PersistEntity ObjectEntity(string jsonObject, Persistence persist) { JObject obj = JObject.Parse(jsonObject); var entity = new PersistEntity(); entity.Json = LessPretty(obj.ToString()); // Read top-level attributes to find variable values foreach (var attrib in obj.Children()) { JProperty prop = attrib as JProperty; if (persist.OutputVars.Contains(prop.Name)) { string value = prop.Value.ToString(Formatting.None); if (value.Length > 1 && value[0] == '"' && value[value.Length - 1] == '"') { entity.PersistValues.Add(prop.Name, value.Substring(1, value.Length - 2)); } else { entity.PersistValues.Add(prop.Name, value); } } } return(entity); }
private void WriteSingle(string folder, string fileDef, PersistEntity entity) { string filename = Path.Combine(folder, entity.GetFilename(fileDef)); if (File.Exists(filename)) { Console.WriteLine($"Overwriting file: {filename}"); } try { File.WriteAllText(filename, entity.Json); } catch (Exception e) { throw new Exception($"Failed to write file '{filename}': {e.Message}"); } }