- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我对 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);
});
}
{ "timestamp":"2020-01-03T00:20:22Z", "event":"Rank", "Rank1":3, "Rank2":8 }
{ "timestamp":"2020-01-03T00:20:22Z", "event":"Progress", "Task1":56, "Task2":100 }
{ "timestamp":"2020-01-03T00:20:22Z", "event":"Reputation", "Nation":75.000000, "State":75.000000 }
{ "timestamp":"2020-01-03T00:20:27Z", "event":"Music", "MusicTrack":"NoTrack" }
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
}
event
字段并使用它来确定要实例化的类。
timestamp
将保留该行,然后将每个事件的字段填充为类的属性。
Newtonsoft.Json
进入 Visual Studio,我认为这本身就有能力做到这一点。
最佳答案
此代码适用于我的机器。您需要为 .log 文件中的所有其他事件添加事件子类(派生自 BaseEvent
的那些,即 RankEvent
),并将属性添加到 JsonEvent
这些的类并将值添加到 EventType
并更新 switch statement
.
我是如何做到的:
{ "timestamp":"2020-01-03T00:20:22Z", "event":"Rank", "Rank1":3, "Rank2":8 }
JsonEvent
从所有的行类。 BaseEvent
具有共同属性(在这种情况下只是 Timestamp
)BaseEvent
的子类对于每个事件,即 RankEvent
EventType
解析 "event"
属性(property)。 jsonEvent
)并查看 EventType
知道我应该创建哪个子类。 newEvent
)解析/反序列化为一个列表 List<BaseEvent>
事件列表
循环完成后,eventList
变量已填充并准备在程序的其余部分中使用。
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
}
}
eventList
快速观看:
补充阅读:
将 Json 解析为 C#
How can I parse JSON with C#?
https://www.jerriepelser.com/blog/deserialize-different-json-object-same-class/
在 Visual Studio 中调试
(总是用 F9 在一行上设置断点,然后按 F5 并用 F10/F11 单步执行代码,它可以深入了解代码的行为方式)
https://docs.microsoft.com/en-us/visualstudio/debugger/navigating-through-code-with-the-debugger?view=vs-2019
从 Json 创建 C# 类的工具:
https://app.quicktype.io/#l=cs&r=json2csharp
https://marketplace.visualstudio.com/items?itemName=DangKhuong.JSONtoC
更新:
我制作了一个额外的脚本,为您创建上述 C# 子类:
只需运行这个脚本,所有的类(包括 Program.cs
)都会被创建。
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());
}
}
}
}
关于c# - 从 JSON 文件在 C# 中创建一个类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59588372/
#include using namespace std; class C{ private: int value; public: C(){ value = 0;
这个问题已经有答案了: What is the difference between char a[] = ?string?; and char *p = ?string?;? (8 个回答) 已关闭
关闭。此题需要details or clarity 。目前不接受答案。 想要改进这个问题吗?通过 editing this post 添加详细信息并澄清问题. 已关闭 7 年前。 此帖子已于 8 个月
除了调试之外,是否有任何针对 c、c++ 或 c# 的测试工具,其工作原理类似于将独立函数复制粘贴到某个文本框,然后在其他文本框中输入参数? 最佳答案 也许您会考虑单元测试。我推荐你谷歌测试和谷歌模拟
我想在第二台显示器中移动一个窗口 (HWND)。问题是我尝试了很多方法,例如将分辨率加倍或输入负值,但它永远无法将窗口放在我的第二台显示器上。 关于如何在 C/C++/c# 中执行此操作的任何线索 最
我正在寻找 C/C++/C## 中不同类型 DES 的现有实现。我的运行平台是Windows XP/Vista/7。 我正在尝试编写一个 C# 程序,它将使用 DES 算法进行加密和解密。我需要一些实
很难说出这里要问什么。这个问题模棱两可、含糊不清、不完整、过于宽泛或夸夸其谈,无法以目前的形式得到合理的回答。如需帮助澄清此问题以便重新打开,visit the help center . 关闭 1
有没有办法强制将另一个 窗口置于顶部? 不是应用程序的窗口,而是另一个已经在系统上运行的窗口。 (Windows, C/C++/C#) 最佳答案 SetWindowPos(that_window_ha
假设您可以在 C/C++ 或 Csharp 之间做出选择,并且您打算在 Windows 和 Linux 服务器上运行同一服务器的多个实例,那么构建套接字服务器应用程序的最明智选择是什么? 最佳答案 如
你们能告诉我它们之间的区别吗? 顺便问一下,有什么叫C++库或C库的吗? 最佳答案 C++ 标准库 和 C 标准库 是 C++ 和 C 标准定义的库,提供给 C++ 和 C 程序使用。那是那些词的共同
下面的测试代码,我将输出信息放在注释中。我使用的是 gcc 4.8.5 和 Centos 7.2。 #include #include class C { public:
很难说出这里问的是什么。这个问题是含糊的、模糊的、不完整的、过于宽泛的或修辞性的,无法以目前的形式得到合理的回答。如需帮助澄清此问题以便重新打开它,visit the help center 。 已关
我的客户将使用名为 annoucement 的结构/类与客户通信。我想我会用 C++ 编写服务器。会有很多不同的类继承annoucement。我的问题是通过网络将这些类发送给客户端 我想也许我应该使用
我在 C# 中有以下函数: public Matrix ConcatDescriptors(IList> descriptors) { int cols = descriptors[0].Co
我有一个项目要编写一个函数来对某些数据执行某些操作。我可以用 C/C++ 编写代码,但我不想与雇主共享该函数的代码。相反,我只想让他有权在他自己的代码中调用该函数。是否可以?我想到了这两种方法 - 在
我使用的是编写糟糕的第 3 方 (C/C++) Api。我从托管代码(C++/CLI)中使用它。有时会出现“访问冲突错误”。这使整个应用程序崩溃。我知道我无法处理这些错误[如果指针访问非法内存位置等,
关闭。这个问题不符合Stack Overflow guidelines .它目前不接受答案。 我们不允许提问寻求书籍、工具、软件库等的推荐。您可以编辑问题,以便用事实和引用来回答。 关闭 7 年前。
已关闭。此问题不符合Stack Overflow guidelines 。目前不接受答案。 要求我们推荐或查找工具、库或最喜欢的场外资源的问题对于 Stack Overflow 来说是偏离主题的,因为
我有一些 C 代码,将使用 P/Invoke 从 C# 调用。我正在尝试为这个 C 函数定义一个 C# 等效项。 SomeData* DoSomething(); struct SomeData {
这个问题已经有答案了: Why are these constructs using pre and post-increment undefined behavior? (14 个回答) 已关闭 6
我是一名优秀的程序员,十分优秀!