private JSDType ObjSpec(JToken obj, string propName, JSONParseOptions opts) { if (obj is JObject) { TypeDef current = new TypeDef(); JObject jobj = (JObject)obj; if (opts.DetectFakeArrays) { JArray tryArr = FakeArrayConvert(jobj); if (tryArr != null) { return(ArrSpec(tryArr, propName, opts)); } } var props = jobj.Properties(); foreach (var prop in props) { JSDType jsdt = ObjSpec(prop.Value, prop.Name, opts); current.Properties.Add(prop.Name, jsdt); } return(SquashType(current, propName, opts).JSDType); } else if (obj is JArray) { return(ArrSpec((JArray)obj, propName, opts)); } else if (obj is JValue) { return(JSDType.TranslatePrimitive(((JValue)obj).Value?.GetType())); } throw new Exception("obj must be either a JObject, JArray, or JValue"); }
private JSDType ArrSpec(JArray arr, string propName, JSONParseOptions opts) { if (arr.Count == 0) { return(JSDType.AnyArray); } Type[] ts = arr.Select(x => x.GetType()).ToArray(); int classCount = ts.Count(x => x.IsClass); List <JSDType> arrTypes = new List <JSDType>(); int processed = 0; foreach (var elem in arr) { var spec = ObjSpec(elem, new Pluralizer().Singularize(propName), opts); if (!spec.IsAny) { arrTypes.Add(spec); processed++; if (processed >= opts.MaxArrayAnalysis) { break; } } } string[] rawTypes = arrTypes.Where(x => !x.IsAny).SelectMany(x => x.Types).Distinct().ToArray(); if (rawTypes.Length == 0) { return(JSDType.AnyArray); } return(new JSDType(rawTypes) { IsArray = true }); }
public static JSDScope GenerateFrom(JToken obj, JSONParseOptions opts = null) { JSDScope scope = new JSDScope(); JSONParseOptions optsval = opts ?? new JSONParseOptions(); JSDType rootType = scope.ObjSpec(obj, null, optsval); TypeDef rootTypeDef = scope.TypeDefinitions.First(x => x.JSDType.Equals(rootType)); scope.TypeDefinitions.Remove(rootTypeDef); scope.TypeDefinitions.Add(rootTypeDef); scope.TypeDefinitions.Reverse();// move root typedef to the front of list return(scope); }
static void Main(string[] args) { try { string JSONInput = null; string JSONFilePath = null; string OutputFilePath = null; string SchemaFilePath = null; bool shouldShowHelp = false; var parseOptions = new JSDoc.JSONParseOptions(); options = new OptionSet { { "j|json=", "Inline JSON input", f => { JSONInput = f; } }, { "f|file=", "Path to a file containing a JSON object", f => { if (!File.Exists(f)) { throw new OptionException($"File \"{f}\" not found or inaccessible", "--file"); } JSONFilePath = f; } },
private TypeDef SquashType(TypeDef t, string propName, JSONParseOptions opts) { foreach (TypeDef td in TypeDefinitions) { if (td.Properties.TrySquash(t.Properties, opts.MaxMultiType)) { return(td); } } propName = propName ?? "MyType"; if (TypeDefinitions.Any(x => x.Name == propName)) { int i = 1; while (TypeDefinitions.Any(x => x.Name == propName + "_" + i)) { i++; } propName += "_" + i; } t.Name = propName; TypeDefinitions.Add(t); return(t); }