AssignName() public method

public AssignName ( string name ) : void
name string
return void
        public StringBuilder GenerateClasses(string jsonInput, out string errorMessage)
        {
            errorMessage = string.Empty;
            try
            {
                JObject[] examples = null;
                try
                {
                    using (StringReader sr = new StringReader(jsonInput))
                        using (JsonTextReader reader = new JsonTextReader(sr))
                        {
                            JToken json = JToken.ReadFrom(reader);
                            if (json is JArray jArray)
                            {
                                examples = jArray.Cast <JObject>().ToArray();
                            }
                            else if (json is JObject jObject)
                            {
                                examples = new[] { jObject };
                            }
                        }
                }
                catch (Exception ex)
                {
                    errorMessage = "Exception: " + ex.Message;
                    return(new StringBuilder());
                }

                if (this.CodeWriter == null)
                {
                    this.CodeWriter = new CSharpCodeWriter();
                }

                this.Types = new List <JsonType>();
                this.Names.Add("Root");
                JsonType rootType = new JsonType(this, examples[0]);
                rootType.IsRoot = true;
                rootType.AssignName("Root");
                this.GenerateClass(examples, rootType);

                this.Types = this.HandleDuplicateClasses(this.Types);

                StringBuilder builder = new StringBuilder();
                this.WriteClassesToFile(builder, this.Types);

                return(builder);
            }
            catch (Exception ex)
            {
                errorMessage = ex.Message + Environment.NewLine + ex.StackTrace;
                return(new StringBuilder());
            }
        }
        public StringBuilder GenerateClasses(string jsonInput, out string errorMessage)
        {
            errorMessage = string.Empty;
            try
            {
                JObject[] examples = null;
                try
                {
                    using (var sr = new StringReader(jsonInput))
                        using (var reader = new JsonTextReader(sr))
                        {
                            var json = JToken.ReadFrom(reader);
                            if (json is JArray)
                            {
                                examples = ((JArray)json).Cast <JObject>().ToArray();
                            }
                            else if (json is JObject)
                            {
                                examples = new[] { (JObject)json };
                            }
                        }
                }
                catch (Exception ex)
                {
                    errorMessage = "Wrong JSON format";
                    return(new StringBuilder());
                }

                if (CodeWriter == null)
                {
                    CodeWriter = new CSharpCodeWriter();
                }

                Types = new List <JsonType>();
                Names.Add("Root");
                var rootType = new JsonType(this, examples[0]);
                rootType.IsRoot = true;
                rootType.AssignName("Root");
                GenerateClass(examples, rootType);
                StringBuilder builder = new StringBuilder();
                WriteClassesToFile(builder, Types);

                return(builder);
            }
            catch (Exception ex)
            {
                errorMessage = ex.Message + Environment.NewLine + ex.StackTrace;
                return(new StringBuilder());
            }
        }
Esempio n. 3
0
        public void GenerateClasses()
        {
            if (CodeWriter == null)
            {
                CodeWriter = new CSharpCodeWriter();
            }
            if (ExplicitDeserialization && !(CodeWriter is CSharpCodeWriter))
            {
                throw new ArgumentException("Explicit deserialization is obsolete and is only supported by the C# provider.");
            }

            if (used)
            {
                throw new InvalidOperationException("This instance of JsonClassGenerator has already been used. Please create a new instance.");
            }
            used = true;


            var writeToDisk = TargetFolder != null;

            if (writeToDisk && !Directory.Exists(TargetFolder))
            {
                Directory.CreateDirectory(TargetFolder);
            }


            JObject[] examples;
            var       example = Example.StartsWith("HTTP/") ? Example.Substring(Example.IndexOf("\r\n\r\n")) : Example;

            using (var sr = new StringReader(example))
                using (var reader = new JsonTextReader(sr))
                {
                    var json = JToken.ReadFrom(reader);
                    if (json is JArray)
                    {
                        examples = ((JArray)json).Cast <JObject>().ToArray();
                    }
                    else if (json is JObject)
                    {
                        examples = new[] { (JObject)json };
                    }
                    else
                    {
                        throw new Exception("Sample JSON must be either a JSON array, or a JSON object.");
                    }
                }


            Types = new List <JsonType>();
            Names.Add(MainClass);
            var rootType = new JsonType(this, examples[0]);

            rootType.IsRoot = false;
            rootType.AssignName(MainClass);
            GenerateClass(examples, rootType);

            if (writeToDisk)
            {
                var parentFolder = System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location);
                if (writeToDisk && !NoHelperClass && ExplicitDeserialization)
                {
                    File.WriteAllBytes(Path.Combine(TargetFolder, "JsonClassHelper.cs"), Properties.Resources.JsonClassHelper);
                }
                if (SingleFile)
                {
                    WriteClassesToFile(Path.Combine(TargetFolder, MainClass + CodeWriter.FileExtension), Types);
                }
                else
                {
                    foreach (var type in Types)
                    {
                        var folder = TargetFolder;
                        if (!UseNestedClasses && !type.IsRoot && SecondaryNamespace != null)
                        {
                            var s = SecondaryNamespace;
                            if (s.StartsWith(Namespace + "."))
                            {
                                s = s.Substring(Namespace.Length + 1);
                            }
                            folder = Path.Combine(folder, s);
                            Directory.CreateDirectory(folder);
                        }
                        WriteClassesToFile(Path.Combine(folder, (UseNestedClasses && !type.IsRoot ? MainClass + "." : string.Empty) + type.AssignedName + CodeWriter.FileExtension), new[] { type });
                    }
                }
            }
            else if (OutputStream != null)
            {
                WriteClassesToFile(OutputStream, Types);
            }
        }
Esempio n. 4
0
        public void GenerateClasses()
        {
            if (CodeWriter == null) CodeWriter = new CSharpCodeWriter();
            if (ExplicitDeserialization && !(CodeWriter is CSharpCodeWriter)) throw new ArgumentException("Explicit deserialization is obsolete and is only supported by the C# provider.");

            if (used) throw new InvalidOperationException("This instance of JsonClassGenerator has already been used. Please create a new instance.");
            used = true;

            var writeToDisk = TargetFolder != null;
            if (writeToDisk && !Directory.Exists(TargetFolder)) Directory.CreateDirectory(TargetFolder);

            JObject[] examples;
            var example = Example.StartsWith("HTTP/") ? Example.Substring(Example.IndexOf("\r\n\r\n")) : Example;
            using (var sr = new StringReader(example))
            using (var reader = new JsonTextReader(sr))
            {
                var json = JToken.ReadFrom(reader);
                if (json is JArray)
                {
                    examples = ((JArray)json).Cast<JObject>().ToArray();
                }
                else if (json is JObject)
                {
                    examples = new[] { (JObject)json };
                }
                else
                {
                    throw new Exception("Sample JSON must be either a JSON array, or a JSON object.");
                }
            }

            Types = new List<JsonType>();
            Names.Add(MainClass);
            var rootType = new JsonType(this, examples[0]);
            rootType.IsRoot = true;
            rootType.AssignName(MainClass);
            GenerateClass(examples, rootType);

            if (writeToDisk)
            {

                var parentFolder = System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location);
                if (writeToDisk && !NoHelperClass && ExplicitDeserialization) File.WriteAllBytes(Path.Combine(TargetFolder, "JsonClassHelper.cs"), Properties.Resources.JsonClassHelper);
                if (SingleFile)
                {
                    WriteClassesToFile(Path.Combine(TargetFolder, MainClass + CodeWriter.FileExtension), Types);
                }
                else
                {

                    foreach (var type in Types)
                    {
                        var folder = TargetFolder;
                        if (!UseNestedClasses && !type.IsRoot && SecondaryNamespace != null)
                        {
                            var s = SecondaryNamespace;
                            if (s.StartsWith(Namespace + ".")) s = s.Substring(Namespace.Length + 1);
                            folder = Path.Combine(folder, s);
                            Directory.CreateDirectory(folder);
                        }
                        WriteClassesToFile(Path.Combine(folder, (UseNestedClasses && !type.IsRoot ? MainClass + "." : string.Empty) + type.AssignedName + CodeWriter.FileExtension), new[] { type });
                    }
                }
            }
            else if (OutputStream != null)
            {
                WriteClassesToFile(OutputStream, Types);
            }
        }
        private void GenerateClass(JObject[] examples, JsonType type)
        {
            Dictionary <String, JsonType>       jsonFields    = new Dictionary <string, JsonType>();
            Dictionary <String, List <Object> > fieldExamples = new Dictionary <string, List <object> >();

            Boolean first = true;

            foreach (JObject obj in examples)
            {
                foreach (JProperty prop in obj.Properties())
                {
                    JsonType fieldType;
                    JsonType currentType = new JsonType(this, prop.Value);
                    String   propName    = prop.Name;

                    if (jsonFields.TryGetValue(propName, out fieldType))
                    {
                        JsonType commonType = fieldType.GetCommonType(currentType);

                        jsonFields[propName] = commonType;
                    }
                    else
                    {
                        JsonType commonType = currentType;
                        if (first)
                        {
                            commonType = commonType.MaybeMakeNullable(this);
                        }
                        else
                        {
                            commonType = commonType.GetCommonType(JsonType.GetNull(this));
                        }
                        jsonFields.Add(propName, commonType);
                        fieldExamples[propName] = new List <object>();
                    }

                    List <Object> fe  = fieldExamples[propName];
                    JToken        val = prop.Value;
                    if (val.Type == JTokenType.Null || val.Type == JTokenType.Undefined)
                    {
                        if (!fe.Contains(null))
                        {
                            fe.Insert(0, null);
                        }
                    }
                    else
                    {
                        Object v = val.Type == JTokenType.Array || val.Type == JTokenType.Object ? val : val.Value <object>();
                        if (!fe.Any(x => v.Equals(x)))
                        {
                            fe.Add(v);
                        }
                    }
                }
                first = false;
            }

            if (this.UseNestedClasses)
            {
                foreach (KeyValuePair <String, JsonType> field in jsonFields)
                {
                    this.Names.Add(field.Key.ToLower());
                }
            }

            foreach (KeyValuePair <String, JsonType> field in jsonFields)
            {
                JsonType fieldType = field.Value;
                if (fieldType.Type == JsonTypeEnum.Object)
                {
                    List <JObject> subexamples = new List <JObject>(examples.Length);
                    foreach (JObject obj in examples)
                    {
                        JToken value;
                        if (obj.TryGetValue(field.Key, out value))
                        {
                            if (value.Type == JTokenType.Object)
                            {
                                subexamples.Add((JObject)value);
                            }
                        }
                    }

                    fieldType.AssignOriginalName(field.Key);
                    fieldType.AssignName(this.CreateUniqueClassName(field.Key));
                    fieldType.AssignNewAssignedName(ToTitleCase(field.Key));

                    this.GenerateClass(subexamples.ToArray(), fieldType);
                }

                if (fieldType.InternalType != null && fieldType.InternalType.Type == JsonTypeEnum.Object)
                {
                    List <JObject> subexamples = new List <JObject>(examples.Length);
                    foreach (JObject obj in examples)
                    {
                        JToken value;
                        if (obj.TryGetValue(field.Key, out value))
                        {
                            if (value.Type == JTokenType.Array)
                            {
                                if (value.Count() > 50)
                                {
                                    JArray takeABunchOfItems = (JArray)value; // Take like 30 items from the array this will increase the chance of getting all the objects accuralty while not analyzing all the data
                                    int    count             = 0;
                                    foreach (JToken item in (JArray)takeABunchOfItems)
                                    {
                                        if (count > 50)
                                        {
                                            break;
                                        }

                                        // if (!(item is JObject)) throw new NotSupportedException("Arrays of non-objects are not supported yet.");
                                        if ((item is JObject))
                                        {
                                            subexamples.Add((JObject)item);
                                        }
                                        ++count;
                                    }
                                }
                                else
                                {
                                    foreach (JToken item in (JArray)value)
                                    {
                                        // if (!(item is JObject)) throw new NotSupportedException("Arrays of non-objects are not supported yet.");
                                        if ((item is JObject))
                                        {
                                            subexamples.Add((JObject)item);
                                        }
                                    }
                                }
                            }
                            else if (value.Type == JTokenType.Object) //TODO J2C : ONLY LOOP OVER 50 OBJECT AND NOT THE WHOLE THING
                            {
                                foreach (KeyValuePair <String, JToken> item in (JObject)value)
                                {
                                    // if (!(item.Value is JObject)) throw new NotSupportedException("Arrays of non-objects are not supported yet.");
                                    if ((item.Value is JObject))
                                    {
                                        subexamples.Add((JObject)item.Value);
                                    }
                                }
                            }
                        }
                    }

                    field.Value.InternalType.AssignOriginalName(field.Key);
                    field.Value.InternalType.AssignName(this.CreateUniqueClassNameFromPlural(field.Key));
                    field.Value.InternalType.AssignNewAssignedName(this.pluralizationService.Singularize(ToTitleCase(field.Key)));

                    this.GenerateClass(subexamples.ToArray(), field.Value.InternalType);
                }
            }

            type.Fields = jsonFields.Select(x => new FieldInfo(this, x.Key, x.Value, this.UsePascalCase, this.UseJsonAttributes, this.UseJsonPropertyName, fieldExamples[x.Key])).ToList();

            if (!string.IsNullOrEmpty(type.AssignedName))
            {
                this.Types.Add(type);
            }
        }