C# 从JSON文件在C中创建类

C# 从JSON文件在C中创建类,c#,json.net,C#,Json.net,我对C非常陌生,虽然我在几年前就涉足过VB 我创建了一个带有多行文本框的基本Windows窗体,并将文本文件的内容写入文本框: public Form1() { InitializeComponent(); List<string> lines = File.ReadAllLines(@"X:\Log Files\01.log").ToList(); lines.ForEach(l => {

我对C非常陌生,虽然我在几年前就涉足过VB

我创建了一个带有多行文本框的基本Windows窗体,并将文本文件的内容写入文本框:

public Form1()
    {
        InitializeComponent();

        List<string> lines = File.ReadAllLines(@"X:\Log Files\01.log").ToList();

        lines.ForEach(l => {

            textBox1.AppendText(l);
            textBox1.AppendText(Environment.NewLine);
                    });

    }
我想根据事件类型创建对象。比如:

   public Progress(int time, int t1, int t2)
   {
        this.timestamp = time;  //'time' is the timestamp value from the line
        this.task1 = t1;        //'t1' is the Task1 value from the line
        this.task2 = t2;        //'t2' is the Task2 value from the line
   }
读取文件时,它将获取事件字段并使用该字段确定要实例化的类。该行的时间戳将被保留,每个事件的字段将作为类的属性填充

我已经将Newtonsoft.Json安装到了VisualStudio中,我认为它本身就有能力做到这一点

但是,我在文档中看不到如何做到这一点

谁能给我指一下正确的方向吗


谢谢

我可以想到两种可能性。两者都不是很漂亮:

创建具有所有属性的单个类 检查每一行是否出现诸如排名、任务、, 国家基于此,您可以选择要创建的类。 我想到了第三个选择。您可以为Json.net编写自己的转换器:


这个代码在我的机器上运行。您需要添加从BaseEvent派生的事件子类,即.log文件中所有其他事件的RankEvent,还需要为这些事件向JSOneEvent类添加属性,向EventType添加值,并更新switch语句

我是如何做到这一点的:

我从.log文件中复制了每一行 即{时间戳:2020-01-03T00:20:22Z,事件:秩,Rank1:3,Rank2:8} 我将该行粘贴到左侧窗口中,以获得一个C类,然后从所有行创建一个组合的JsonEvent类。 我之所以这样做是因为在每次解析循环之后,一些属性将为null 我制作了一个基类BaseEvent,它具有公共属性,在本例中只是时间戳 我为每个事件创建了BaseEvent的子类,即RankEvent 我创建了一个事件枚举EventType来解析事件属性。 我循环了所有的行,对于每一行,我都将该行反序列化为一个JsonEvent C类JsonEvent,并查看EventType以了解应该创建哪个子类。 对于每个循环,我将一个子类newEvent解析/反序列化为一个列表eventList 循环完成后,将填充eventList变量并准备在程序的其余部分中使用。
这看起来不像JSON,它看起来像以换行符分隔的JSON,基本上是一系列连接在一起的JSON对象。要读取此类文件,请参阅。有关将来的信息,请参阅textbox1.Text=file.ReadAllTextc:\\my.txt;是将文件读入文本框的更简洁的方法。使用是快速生成序列化和反序列化jsonJoel的c类的好方法,非常感谢所有的细节。我今天有一些工作要做,计划明天或今晚玩这个。我真的很感谢额外阅读的链接。我需要对自己进行这方面的教育。@jchornsey没问题!只是为了好玩,我制作了一个额外的脚本来为您创建上面的C类。查看更新!我不确定在那种情况下你是不是可以说只是为了好玩。LOL。这些东西太让我不知所措了,我甚至想不出如何更改主窗口标签上的文本来列出事件名称LOL,但我正在学习,多亏了你发布的内容。非常感谢。这无疑让我走上了正确的道路!克里斯蒂安,谢谢你的回答。我来看看这些链接。我对自己写很多东西的能力没有太多信心,更不用说Json.net的转换器了。英雄联盟
   public Progress(int time, int t1, int t2)
   {
        this.timestamp = time;  //'time' is the timestamp value from the line
        this.task1 = t1;        //'t1' is the Task1 value from the line
        this.task2 = t2;        //'t2' is the Task2 value from the line
   }
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.Serialization;

namespace StackOverFlow
{
    public class Program
    {
        static void Main(string[] args)
        {
            var file = @"X:\Log Files\01.log";
            var eventList = ParseEvents(file);
            //TODO Do something
        }

        private static List<BaseEvent> ParseEvents(string file)
        {
            //TODO Encapsulate in a try & catch and add a logger for error handling
            var eventList = new List<BaseEvent>();
            var lines = File.ReadAllLines(file).ToList();
            foreach (var line in lines)
            {
                var jsonEvent = JsonConvert.DeserializeObject<JsonEvent>(line);
                BaseEvent newEvent;
                switch (jsonEvent.EventType)
                {
                    case EventType.Rank:
                        newEvent = new RankEvent(jsonEvent);
                        eventList.Add(newEvent);
                        break;
                    case EventType.Progress:
                        newEvent = new ProgressEvent(jsonEvent);
                        eventList.Add(newEvent);
                        break;
                    case EventType.Reputation:
                        newEvent = new ReputationEvent(jsonEvent);
                        eventList.Add(newEvent);
                        break;
                    case EventType.Music:
                        newEvent = new MusicEvent(jsonEvent);
                        eventList.Add(newEvent);
                        break;

                    //TODO Add more cases for each EventType

                    default:
                        throw new Exception(String.Format("Unknown EventType: {0}", jsonEvent.EventType));
                }
            }

            return eventList;
        }
    }

    //TODO Move classes/enums to a separate folder

    [JsonConverter(typeof(StringEnumConverter))]
    public enum EventType
    {
        [EnumMember(Value = "Rank")]
        Rank,
        [EnumMember(Value = "Progress")]
        Progress,
        [EnumMember(Value = "Reputation")]
        Reputation,
        [EnumMember(Value = "Music")]
        Music,

        //TODO Add more enum values for each "event"
    }

    public abstract class BaseEvent
    {
        public BaseEvent(DateTime timestamp)
        {
            Timestamp = timestamp;
        }
        public DateTime Timestamp { get; set; }
    }

    public class RankEvent : BaseEvent
    {
        public RankEvent(JsonEvent jsonEvent) : base(jsonEvent.Timestamp)
        {
            Rank1 = jsonEvent.Rank1.Value;
            Rank2 = jsonEvent.Rank2.Value;
        }
        public int Rank1 { get; set; }
        public int Rank2 { get; set; }
    }

    public class ProgressEvent : BaseEvent
    {
        public ProgressEvent(JsonEvent jsonEvent) : base(jsonEvent.Timestamp)
        {
            Task1 = jsonEvent.Task1.Value;
            Task2 = jsonEvent.Task2.Value;
        }
        public int Task1 { get; set; }
        public int Task2 { get; set; }
    }

    public class ReputationEvent : BaseEvent
    {
        public ReputationEvent(JsonEvent jsonEvent) : base(jsonEvent.Timestamp)
        {
            Nation = jsonEvent.Nation.Value;
            State = jsonEvent.State.Value;
        }
        public double Nation { get; set; }
        public double State { get; set; }
    }

    public class MusicEvent : BaseEvent
    {
        public MusicEvent(JsonEvent jsonEvent) : base(jsonEvent.Timestamp)
        {
            MusicTrack = jsonEvent.MusicTrack;
        }
        public string MusicTrack { get; set; }
    }

    //TODO Add more derived sub classes of the BaseEvent

    [JsonObject]
    public class JsonEvent
    {
        [JsonProperty("timestamp")]
        public DateTime Timestamp { get; set; }
        [JsonProperty("event")]
        public EventType EventType { get; set; }
        public int? Rank1 { get; set; }
        public int? Rank2 { get; set; }
        public int? Task1 { get; set; }
        public int? Task2 { get; set; }
        public double? Nation { get; set; }
        public double? State { get; set; }
        public string MusicTrack { get; set; }

        //TODO Add more properties
    }
}

using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;

namespace CreateFiles
{
    public class Program
    {
        static void Main(string[] args)
        {
            var file = @"X:\Log Files\01.log";
            var desktop = Environment.GetFolderPath(Environment.SpecialFolder.Desktop);
            //Change outPutPath to your choosing
            var outPutPath = Path.Combine(desktop, "Temp");
            //Change namespaceName to your choosing
            var namespaceName = "StackOverFlow";
            var uniqueList = GetUniqueEventTypeList(file);
            CreateBaseClass(outPutPath, namespaceName);
            CreateEventClasses(uniqueList, outPutPath, namespaceName);
            CreateEnumClass(uniqueList, outPutPath, namespaceName);
            CreateJsonEventClass(uniqueList, outPutPath, namespaceName);
            CreateProgramClass(uniqueList, outPutPath, namespaceName);
            Console.WriteLine($"\nParsing done! Classes parsed to {outPutPath}");
            Console.WriteLine("Press any key to continue.");
            Console.ReadLine();
        }

        private static List<string> GetUniqueEventTypeList(string file)
        {
            var lines = File.ReadAllLines(file).ToList();
            var uniqueEventTypes = new List<string>();
            var uniqueList = new List<string>();

            foreach (var line in lines)
            {
                var json = JObject.Parse(line);
                var eventType = json["event"].Value<string>();
                if (!uniqueEventTypes.Exists(e => e.Equals(eventType)))
                {
                    uniqueEventTypes.Add(eventType);
                    uniqueList.Add(line);
                }
            }
            return uniqueList;
        }

        private static void CreateEventClasses(List<string> lines, string path, string namespaceName)
        {
            foreach (var line in lines)
            {
                var jObj = JObject.Parse(line);
                CreateEventClass(jObj, path, namespaceName);
            }
        }

        public class ParseClass
        {
            public ParseClass(KeyValuePair<string, JToken> obj)
            {
                Name = obj.Key;
                SetType(obj.Value);
            }
            public string Name { get; set; }
            public string Type { get; set; }
            public bool IsPrimitive { get; set; }

            private void SetType(JToken token)
            {
                switch (token.Type)
                {
                    case JTokenType.Integer:
                        Type = "int";
                        IsPrimitive = true;
                        break;
                    case JTokenType.Float:
                        Type = "double";
                        IsPrimitive = true;
                        break;
                    case JTokenType.String:
                        Type = "string";
                        IsPrimitive = false;
                        break;
                    case JTokenType.Boolean:
                        Type = "bool";
                        IsPrimitive = true;
                        break;
                    case JTokenType.Date:
                        Type = "DateTime";
                        IsPrimitive = true;
                        break;
                    case JTokenType.Guid:
                        Type = "Guid";
                        IsPrimitive = true;
                        break;
                    case JTokenType.Uri:
                        Type = "Uri";
                        IsPrimitive = false;
                        break;
                    default:
                        throw new Exception($"Unknown type {token.Type}");
                }
            }
        }

        private static void CreateProgramClass(List<string> lines, string path, string namespaceName)
        {
            Directory.CreateDirectory(path);
            var className = "Program";
            var fileName = $"{className}.cs";
            var file = Path.Combine(path, fileName);

            try
            {
                // Create a new file     
                using (FileStream fsStream = new FileStream(file, FileMode.Create))
                using (StreamWriter sw = new StreamWriter(fsStream, Encoding.UTF8))
                {
                    //The Program class needed these bytes in the beginning to work
                    sw.WriteLine("using Newtonsoft.Json;");
                    sw.WriteLine("using System;");
                    sw.WriteLine("using System.Collections.Generic;");
                    sw.WriteLine("using System.IO;");
                    sw.WriteLine("using System.Linq;");
                    sw.WriteLine("");
                    sw.WriteLine($"namespace {namespaceName}");
                    sw.WriteLine("{");
                    sw.WriteLine($"    public class {className}");
                    sw.WriteLine("    {");
                    sw.WriteLine($"        static void Main(string[] args)");
                    sw.WriteLine("        {");
                    sw.WriteLine("            var file = @\"X:\\Log Files\\01.log\";");
                    sw.WriteLine("            var eventList = ParseEvents(file);");
                    sw.WriteLine("            //TODO Do something");
                    sw.WriteLine("        }");
                    sw.WriteLine("");
                    sw.WriteLine("        private static List<BaseEvent> ParseEvents(string file)");
                    sw.WriteLine("        {");
                    sw.WriteLine("            //TODO Encapsulate in a try & catch and add a logger for error handling");
                    sw.WriteLine("            var eventList = new List<BaseEvent>();");
                    sw.WriteLine("            var lines = File.ReadAllLines(file).ToList();");
                    sw.WriteLine("");
                    sw.WriteLine("            foreach (var line in lines)");
                    sw.WriteLine("            {");
                    sw.WriteLine("                var jsonEvent = JsonConvert.DeserializeObject<JsonEvent>(line);");
                    sw.WriteLine("                BaseEvent newEvent;");
                    sw.WriteLine("                switch (jsonEvent.EventType)");
                    sw.WriteLine("                {");
                    foreach (var line in lines)
                    {
                        var jObj = JObject.Parse(line);
                        var eventType = jObj["event"].Value<string>();
                        sw.WriteLine($"                    case EventType.{eventType}:");
                        sw.WriteLine($"                        newEvent = new {eventType}Event(jsonEvent);");
                        sw.WriteLine($"                        eventList.Add(newEvent);");
                        sw.WriteLine($"                        break;");
                    }
                    sw.WriteLine("                    default:");
                    sw.WriteLine("                        throw new Exception(String.Format(\"Unknown EventType: {0} \", jsonEvent.EventType));");
                    sw.WriteLine("                }");
                    sw.WriteLine("            }");
                    sw.WriteLine("            return eventList;");
                    sw.WriteLine("        }");
                    sw.WriteLine("    }");
                    sw.WriteLine("}");
                }
                Console.WriteLine($"Created {fileName}.");
            }
            catch (Exception Ex)
            {
                Console.WriteLine(Ex.ToString());
            }
        }

        private static void CreateEnumClass(List<string> lines, string path, string namespaceName)
        {
            Directory.CreateDirectory(Path.Combine(path));
            var className = "EventType";
            var fileName = $"{className}.cs";
            var file = Path.Combine(path, fileName);
            FileInfo fi = new FileInfo(file);

            try
            {
                // Check if file already exists. If yes, throw exception.     
                if (fi.Exists)
                {
                    throw new Exception($"{file} already exists!");
                }

                // Create a new file     
                using (FileStream fsStream = new FileStream(file, FileMode.Create))
                using (StreamWriter sw = new StreamWriter(fsStream, Encoding.UTF8))
                {
                    sw.WriteLine("using Newtonsoft.Json;");
                    sw.WriteLine("using Newtonsoft.Json.Converters;");
                    sw.WriteLine("using System.Runtime.Serialization;");
                    sw.WriteLine("");
                    sw.WriteLine($"namespace {namespaceName}");
                    sw.WriteLine("{");
                    sw.WriteLine($"    [JsonConverter(typeof(StringEnumConverter))]");
                    sw.WriteLine($"    public enum {className}");
                    sw.WriteLine("    {");
                    foreach (var line in lines)
                    {
                        var jObj = JObject.Parse(line);
                        var eventType = jObj["event"].Value<string>();
                        sw.WriteLine($"        [EnumMember(Value = \"{eventType}\")]");
                        sw.WriteLine($"        {eventType},");
                    }
                    sw.WriteLine("    }");
                    sw.WriteLine("}");
                }
                Console.WriteLine($"Created {fileName}.");
            }
            catch (Exception Ex)
            {
                Console.WriteLine(Ex.ToString());
            }
        }

        private static void CreateJsonEventClass(List<string> lines, string path, string namespaceName)
        {

            Directory.CreateDirectory(path);
            var className = "JsonEvent";
            var fileName = $"{className}.cs";
            var file = Path.Combine(path, fileName);
            FileInfo fi = new FileInfo(file);

            var propertyList = new List<ParseClass>();
            foreach (var line in lines)
            {
                var jObject = JObject.Parse(line);
                foreach (var obj in jObject)
                {
                    if (!(obj.Key.Equals("event") || obj.Key.Equals("timestamp")))
                    {
                        propertyList.Add(new ParseClass(obj));
                    }
                }
            }

            try
            {
                // Check if file already exists. If yes, throw exception.     
                if (fi.Exists)
                {
                    throw new Exception($"{file} already exists!");
                }
                // Create a new file     
                using (FileStream fsStream = new FileStream(file, FileMode.Create))
                using (StreamWriter sw = new StreamWriter(fsStream, Encoding.UTF8))
                {
                    sw.WriteLine("using Newtonsoft.Json;");
                    sw.WriteLine("using System;");
                    sw.WriteLine("");
                    sw.WriteLine($"namespace {namespaceName}");
                    sw.WriteLine("{");
                    sw.WriteLine($"    [JsonObject]");
                    sw.WriteLine($"    public class {className}");
                    sw.WriteLine("{");
                    sw.WriteLine("        [JsonProperty(\"timestamp\")]");
                    sw.WriteLine("        public DateTime Timestamp { get; set; }");
                    sw.WriteLine("        [JsonProperty(\"event\")]");
                    sw.WriteLine("        public EventType EventType { get; set; }");
                    foreach (var property in propertyList)
                    {
                        var type = property.IsPrimitive ? property.Type + "?" : property.Type;
                        sw.WriteLine("        public " + type + " " + property.Name + " { get; set; }");
                    }
                    sw.WriteLine("    }");
                    sw.WriteLine("}");
                }
                Console.WriteLine($"Created {fileName}.");
            }
            catch (Exception Ex)
            {
                Console.WriteLine(Ex.ToString());
            }
        }

        private static void CreateBaseClass(string path, string namespaceName)
        {
            Directory.CreateDirectory(path);
            var className = $"BaseEvent";
            var fileName = $"{className}.cs";
            var file = Path.Combine(path, fileName);

            FileInfo fi = new FileInfo(file);

            try
            {
                // Check if file already exists. If yes, throw exception.     
                if (fi.Exists)
                {
                    throw new Exception($"{file} already exists!");
                }

                // Create a new file     
                using (StreamWriter sw = fi.CreateText())
                {
                    sw.WriteLine($"using System;");
                    sw.WriteLine("");
                    sw.WriteLine($"namespace {namespaceName}");
                    sw.WriteLine("{");
                    sw.WriteLine($"    public abstract class BaseEvent");
                    sw.WriteLine("    {");
                    sw.WriteLine($"        public BaseEvent(DateTime timestamp)");
                    sw.WriteLine("        {");
                    sw.WriteLine($"            Timestamp = timestamp;");
                    sw.WriteLine("        }");
                    sw.WriteLine("        public DateTime Timestamp { get; set; }");
                    sw.WriteLine("    }");
                    sw.WriteLine("}");
                }
                Console.WriteLine($"Created {fileName}.");
            }
            catch (Exception Ex)
            {
                Console.WriteLine(Ex.ToString());
            }
        }

        private static void CreateEventClass(JObject jObject, string path, string namespaceName)
        {
            Directory.CreateDirectory(path);
            var eventName = $"{jObject["event"].Value<string>()}";
            var className = $"{eventName}Event";
            var fileName = $"{className}.cs";
            var file = Path.Combine(path, fileName);

            FileInfo fi = new FileInfo(file);

            var propertyList = new List<ParseClass>();
            foreach (var obj in jObject)
            {
                if (!(obj.Key.Equals("event") || obj.Key.Equals("timestamp")))
                {
                    propertyList.Add(new ParseClass(obj));
                }
            }

            try
            {
                // Check if file already exists. If yes, throw exception.     
                if (fi.Exists)
                {
                    throw new Exception($"{file} already exists!");
                }

                // Create a new file     
                using (FileStream fsStream = new FileStream(file, FileMode.Create))
                using (StreamWriter sw = new StreamWriter(fsStream, Encoding.UTF8))
                {
                    sw.WriteLine($"namespace {namespaceName}");
                    sw.WriteLine("{");
                    sw.WriteLine($"    public class {className} : BaseEvent");
                    sw.WriteLine("    {");
                    sw.WriteLine($"        public {className}(JsonEvent jsonEvent) : base(jsonEvent.Timestamp)");
                    sw.WriteLine("        {");
                    foreach (var property in propertyList)
                    {
                        var name = property.IsPrimitive ? $"{property.Name}.Value" : $"{property.Name}";
                        sw.WriteLine($"            {property.Name} = jsonEvent.{name};");
                    }
                    sw.WriteLine("        }");
                    foreach (var property in propertyList)
                    {
                        sw.WriteLine("        public " + property.Type + " " + property.Name + " { get; set; }");
                    }
                    sw.WriteLine("    }");
                    sw.WriteLine("}");
                }
                Console.WriteLine($"Created {fileName}.");
            }
            catch (Exception Ex)
            {
                Console.WriteLine(Ex.ToString());
            }
        }
    }
}