Inheritance: IJsonClassGeneratorConfig
        void PasteJson(Clipboard c, string text)
        {
            if (string.IsNullOrEmpty (text)) {
                InsertCSharp (string.Empty);
                return;
            }

            var gen = new JsonClassGenerator {
                Example = text,
                MainClass = "RootObject",
                UseProperties = true,
                CodeWriter = new CSharpCodeWriter ()
            };

            try {
                using (var sw = new StringWriter ()) {
                    gen.OutputStream = sw;
                    gen.GenerateClasses ();
                    sw.Flush ();
                    var generatedString = sw.ToString ();
                    InsertCSharp (generatedString);
                }
            } catch (Exception ex) {
                Console.WriteLine (ex.Message);
                MessageService.ShowWarning (string.Format ("Invalid JSON: {0}", ex.Message));
            }

            gen = null;
        }
Example #2
0
        private static JsonTypeEnum GetFirstTypeEnum(JToken token)
        {
            JTokenType type = token.HasValues
                ? token.Type
                : (JTokenType)Enum.Parse(typeof(JTokenType),
                                         JsonClassGenerator.ToTitleCase(token.Value <string>()));

            switch (type)
            {
            case JTokenType.Array: return(JsonTypeEnum.Array);

            case JTokenType.Boolean: return(JsonTypeEnum.Boolean);

            case JTokenType.Float: return(JsonTypeEnum.Float);

            case JTokenType.Integer: return(JsonTypeEnum.Integer);

            case JTokenType.Null: return(JsonTypeEnum.NullableSomething);

            case JTokenType.Undefined: return(JsonTypeEnum.NullableSomething);

            case JTokenType.String: return(JsonTypeEnum.String);

            case JTokenType.Object: return(JsonTypeEnum.Object);

            case JTokenType.Date: return(JsonTypeEnum.Date);

            default: return(JsonTypeEnum.Anything);
            }
        }
Example #3
0
        // POST: api/Entity
        public IHttpActionResult Post([FromBody]Entity entity)
        {
            try
            {
                var classGenerator = new JsonClassGenerator();
                classGenerator.MainClass = entity.Name;
                classGenerator.Example = entity.Json;

                var project = string.IsNullOrEmpty(entity.Project) ? "Global" : entity.Project;

                classGenerator.Namespace = project + "." + Config.Models;
                classGenerator.TargetFolder = Path.Combine(Config.ProjectRepository, project, Config.Models);
                Directory.CreateDirectory(classGenerator.TargetFolder);
                classGenerator.UseProperties = true;
                classGenerator.UsePascalCase = true;
                if (entity.EnableDB)
                    classGenerator.GenerateIdField = true;

                var entities = classGenerator.GenerateClasses();

                if (entity.EnableDB)
                {
                    addDBContext(entity.Project, entities);
                }

                return Ok("Entity created successfully");
            }
            catch(Exception ex)
            {
                return InternalServerError(ex);
            }
        }
Example #4
0
 public FieldInfo(IJsonClassGeneratorConfig generator, string jsonMemberName, JsonType type, bool usePascalCase, IList <object> Examples)
 {
     this.generator      = generator;
     this.JsonMemberName = jsonMemberName;
     this.MemberName     = JsonClassGenerator.ToTitleCase(jsonMemberName);
     this.Type           = type;
     this.Examples       = Examples;
 }
Example #5
0
        private JsonClassGenerator Prepare()
        {
            string namespacestr = Request["namespacestr"];
            string mainclass = Request["mainclass"];
            int type = Utils.GetInt(Request["type"]);
            string jsonstr = Request["jsonstr"];

            int internalVis = Utils.GetInt(Request["xsf"]);
            int useField = Utils.GetInt(Request["pf"]);
            int usePascalCase = 1;// Utils.GetInt(Request["mm"]);
            var gen = new JsonClassGenerator();
            //json字符串
            gen.Example = jsonstr;
            //类修饰符 internal=true,public =false
            gen.InternalVisibility = internalVis==0?false:true;
            //具体的处理类 c# vb.net typescript
            switch (type)
            {
                case 1:
                    gen.CodeWriter = new VisualBasicCodeWriter();
                    break;
                case 2:
                    gen.CodeWriter = new TypeScriptCodeWriter();
                    break;
                case 3:
                    //java
                    gen.CodeWriter = new JavaCodeWriter();
                    break;
                default:
                    gen.CodeWriter = new CSharpCodeWriter();
                    break;
            }

            //明确饭序列化
            gen.ExplicitDeserialization =false;
            //命名空间
            gen.Namespace = namespacestr;
            //ExplicitDeserialization=true才能使用
            gen.NoHelperClass = false;
            gen.SecondaryNamespace = null;
            gen.TargetFolder =null;
            //使用属性写法 false=字段写法
            gen.UseProperties = useField==0?true:false;

            gen.MainClass = string.IsNullOrEmpty(mainclass) ? "Root" : mainclass;
            //首字母大写Code   false=骆驼式命名 首字母小写 后面首字母大写twoFeet
            gen.UsePascalCase = usePascalCase==0?true:false;
            //使用嵌套类
            gen.UseNestedClasses =false;
            //使用模糊属性
            gen.ApplyObfuscationAttributes = false;
            gen.SingleFile = true;
            //生成文档范例
            gen.ExamplesInDocumentation = false;

            return gen;
        }
Example #6
0
 public FieldInfo(IJsonClassGeneratorConfig generator, string jsonMemberName, JsonType type, bool usePascalCase, IList <object> Examples)
 {
     this.generator      = generator;
     this.JsonMemberName = jsonMemberName;
     this.MemberName     = Regex.Replace(jsonMemberName, "[^\\w]", "");
     if (usePascalCase)
     {
         MemberName = JsonClassGenerator.ToTitleCase(MemberName);
     }
     this.Type     = type;
     this.Examples = Examples;
 }
Example #7
0
 public FieldInfo(IJsonClassGeneratorConfig generator, string jsonMemberName, JsonType type, bool usePascalCase, IList <object> Examples)
 {
     this.generator      = generator;
     this.JsonMemberName = jsonMemberName;
     this.MemberName     = jsonMemberName;
     if (usePascalCase)
     {
         // This does nothing if the json is already in Title case
         // which may confuse some people when it's turned off
         MemberName = JsonClassGenerator.ToTitleCase(MemberName);
     }
     this.Type     = type;
     this.Examples = Examples;
 }
Example #8
0
        public FieldInfo(IJsonClassGeneratorConfig generator, string jsonMemberName, JsonType type, bool usePascalCase, bool useJsonAttributes, bool useJsonPropertyName, IList <object> Examples)
        {
            this.generator      = generator;
            this.JsonMemberName = jsonMemberName;
            this.MemberName     = jsonMemberName;
            bool constainsSpecialChars = isContainsSpecialChars(MemberName);

            ContainsSpecialChars = constainsSpecialChars;
            if (usePascalCase || useJsonAttributes || useJsonPropertyName || constainsSpecialChars)
            {
                MemberName = JsonClassGenerator.ToTitleCase(MemberName);
            }
            this.Type     = type;
            this.Examples = Examples;
        }
        public FieldInfo(
            IJsonClassGeneratorConfig generator,
            string jsonMemberName,
            JsonType type,
            bool usePascalCase,
            IReadOnlyList <object> examples
            )
        {
            this.generator            = generator ?? throw new ArgumentNullException(nameof(generator));
            this.JsonMemberName       = jsonMemberName ?? throw new ArgumentNullException(nameof(jsonMemberName));
            this.MemberName           = jsonMemberName;
            this.ContainsSpecialChars = IsContainsSpecialChars(this.MemberName);

            if (usePascalCase || this.ContainsSpecialChars)
            {
                this.MemberName = JsonClassGenerator.ToTitleCase(this.MemberName);
            }

            this.Type     = type ?? throw new ArgumentNullException(nameof(type));
            this.Examples = examples ?? Array.Empty <object>();
        }
        private static JsonClassGenerator Prepare(string json, string nameSpace, string targetFolder, string mainClass )
        {
            var gen = new JsonClassGenerator
            {
                Example = json,
                InternalVisibility = true,
                CodeWriter = new CSharpCodeWriter(),
                ExplicitDeserialization = false,
                Namespace = string.IsNullOrEmpty(nameSpace) ? null : nameSpace,
                NoHelperClass = false,
                SecondaryNamespace = null,
                TargetFolder = targetFolder,
                UseProperties = true,
                MainClass = mainClass,
                UsePascalCase = false,
                UseNestedClasses = false,
                ApplyObfuscationAttributes = false,
                SingleFile = false,
                ExamplesInDocumentation = false
            };

            return gen;
        }
Example #11
0
        private string Prepare(string JSON, string classname, int language, bool nest, bool pascal, string propertyAttribute, bool hasGetSet=false)
        {
            if (string.IsNullOrEmpty(JSON))
            {
                return null;
            }

            ICodeWriter writer;

            if (language == 1)
                writer = new CSharpCodeWriter();
            else if (language == 2)
                writer = new VisualBasicCodeWriter();
            else if (language == 3)
                writer = new TypeScriptCodeWriter();
            else if(language == 4)
                writer = new SqlCodeWriter();
            else if(language == 5)
                writer = new JavaCodeWriter();
            else
                writer = new PhpCodeWriter();

            var gen = new JsonClassGenerator();
            gen.Example = JSON;
            gen.InternalVisibility = false;
            gen.CodeWriter = writer;
            gen.ExplicitDeserialization = false;
            if (nest)
                gen.Namespace = "JSONUtils";
            else
                gen.Namespace = null;

            gen.NoHelperClass = false;
            gen.SecondaryNamespace = null;
            gen.UseProperties = (language != 5 && language != 6) || hasGetSet;
            gen.MainClass = classname;
            gen.UsePascalCase = pascal;
            gen.PropertyAttribute = propertyAttribute;

            gen.UseNestedClasses = nest;
            gen.ApplyObfuscationAttributes = false;
            gen.SingleFile = true;
            gen.ExamplesInDocumentation = false;
            
            gen.TargetFolder = null;
            gen.SingleFile = true;

            using (var sw = new StringWriter())
            {
                gen.OutputStream = sw;
                gen.GenerateClasses();
                sw.Flush();

                return sw.ToString();
            }
        }
Example #12
0
 public void AssignName(string name, string originalName)
 {
     AssignedName = JsonClassGenerator.ToTitleCase(name);
     OriginalName = originalName;
 }
        public void GenerateClasses(string nameSpace)
        {
            var numSamples = NumRowsToSample;

            _generatedClasses =
                GetInputFiles()
                    .Select(f =>
                    {
                        // TODO: Be a better error handler
                        try
                        {
                            var fs = new FileStream(f, FileMode.Open);
                            var sr = new StreamReader(fs);
                            var jtr = new JsonTextReader(sr);

                            var examples =
                                Enumerable
                                    .Range(0, numSamples)
                                    .Select(_ =>
                                    {
                                        while (jtr.Read())
                                            if (jtr.TokenType == JsonToken.StartObject)
                                                return JObject.Load(jtr).ToString();
                                        return null;
                                    })
                                    .Where(json => json != null);

                            var examplesJson = String.Format("[{0}]", String.Join(",\r\n", examples));

                            jtr.Close();
                            sr.Close();
                            fs.Close();

                            var className = Path.GetFileNameWithoutExtension(f).SanitiseClassName();
                            var finalNamespace = nameSpace + "." + className + "Input";
                            var outputStream = new MemoryStream();
                            var outputWriter = new StreamWriter(outputStream);

                            var jsg = new JsonClassGenerator
                            {
                                Example = examplesJson,
                                Namespace = finalNamespace,
                                MainClass = className,
                                OutputStream = outputWriter,
                                NoHelperClass = true,
                                UseProperties = true,
                                GeneratePartialClasses = true
                            };

                            jsg.GenerateClasses();

                            outputWriter.Flush();
                            outputStream.Seek(0, SeekOrigin.Begin);

                            var classDef = new StreamReader(outputStream)
                                .ReadToEnd()
                                .Replace("IList<", "List<");

                            classDef =
                                classDef.Substring(classDef.IndexOf(String.Format("namespace {0}", nameSpace),
                                    StringComparison.Ordinal));

                            NamespacesToAdd.Add(finalNamespace);

                            return new JsonFileGeneratedClass(this)
                            {
                                Namespace = finalNamespace,
                                ClassName = className,
                                DataFilePath = f,
                                ClassDefinition = classDef,
                                Success = true
                            };
                        }
                        catch (Exception e)
                        {
                            return new JsonFileGeneratedClass(this)
                            {
                                DataFilePath = f,
                                Success = false,
                                Error = e
                            };
                        }
                    })
                    .ToList();
        }
Example #14
0
        static JsonClassGenerator Prepare(JToken json, string type, string folder,
            string mainNameSpace = "MainNameSpace.Main")
        {
            var gen = new JsonClassGenerator();
            gen.Example = json.ToString();
            gen.InternalVisibility = false;
            gen.CodeWriter = new CSharpCodeWriter();
            gen.ExplicitDeserialization = false;

            gen.Namespace = mainNameSpace;
            gen.NoHelperClass = false;

            gen.TargetFolder = @folder;
            gen.UseProperties = true;
            gen.MainClass = type;

            gen.UsePascalCase = true;
            gen.UseNestedClasses = false;
            gen.ApplyObfuscationAttributes = false;
            gen.SingleFile = true;
            gen.ExamplesInDocumentation = false;
            gen.InheritedClassOrInterface = "ClarizenEntity";
            return gen;
        }
        public void GenerateClasses(string nameSpace)
        {
            try
            {
                var className = Name.SanitiseClassName();

                var finalNamespace = nameSpace + "." + className + "Input";
                var outputStream = new MemoryStream();
                var outputWriter = new StreamWriter(outputStream);

                var jsg = new JsonClassGenerator
                {
                    Example = Json,
                    Namespace = finalNamespace,
                    MainClass = className,
                    OutputStream = outputWriter,
                    NoHelperClass = true,
                    UseProperties = true,
                    GeneratePartialClasses = true
                };

                jsg.GenerateClasses();

                outputWriter.Flush();
                outputStream.Seek(0, SeekOrigin.Begin);

                var classDef = new StreamReader(outputStream)
                    .ReadToEnd()
                    .Replace("IList<", "List<");

                classDef =
                    classDef.Substring(classDef.IndexOf(String.Format("namespace {0}", nameSpace),
                        StringComparison.Ordinal));

                NamespacesToAdd.Add(finalNamespace);

                _generatedClass = new JsonTextGeneratedClass(this)
                {
                    Namespace = finalNamespace,
                    ClassName = className,
                    ClassDefinition = classDef,
                    Success = true
                };
            }
            catch (Exception e)
            {
                _generatedClass = new JsonTextGeneratedClass(this)
                {
                    Success = false,
                    Error = e
                };
            }
        }
        public void GenerateClasses(string nameSpace)
        {
            try
            {
                var req = (HttpWebRequest) HttpWebRequest.Create(Url);
                req.AutomaticDecompression = DecompressionMethods.Deflate | DecompressionMethods.GZip;
                req.UserAgent = @"Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2228.0 Safari/537.36";

                var examplesJson = "";
                using (var sr = new StreamReader(req.GetResponse().GetResponseStream()))
                    examplesJson = sr.ReadToEnd();

                var className = Name.SanitiseClassName();
                var finalNamespace = nameSpace + "." + className + "Input";
                var outputStream = new MemoryStream();
                var outputWriter = new StreamWriter(outputStream);

                var jsg = new JsonClassGenerator
                {
                    Example = examplesJson,
                    Namespace = finalNamespace,
                    MainClass = className,
                    OutputStream = outputWriter,
                    NoHelperClass = true,
                    UseProperties = true,
                    GeneratePartialClasses = true
                };

                jsg.GenerateClasses();

                outputWriter.Flush();
                outputStream.Seek(0, SeekOrigin.Begin);

                var classDef = new StreamReader(outputStream)
                    .ReadToEnd()
                    .Replace("IList<", "List<");

                classDef =
                    classDef.Substring(classDef.IndexOf(String.Format("namespace {0}", nameSpace),
                        StringComparison.Ordinal));

                NamespacesToAdd.Add(finalNamespace);

                GeneratedClasses = new List<IGeneratedClass>
                {
                    new JsonUrlGeneratedClass(this)
                    {
                        Namespace = finalNamespace,
                        ClassName = className,
                        Url = Url,
                        ClassDefinition = classDef,
                        Success = true
                    }
                };
            }
            catch (Exception e)
            {
                GeneratedClasses = new List<IGeneratedClass>
                {
                    new JsonUrlGeneratedClass(this)
                    {
                        Url = Url,
                        Success = false,
                        Error = e
                    }
                };
            }
        }