Hi @Julio Caproni ,
I update my code as below:
using Newtonsoft.Json;
using System.Globalization;
namespace MSTestProject
{
[TestClass]
public class UnitTest2
{
//https://learn.microsoft.com/en-us/answers/questions/954604/spliting-data-from-com-port.html
[TestMethod]
public void Test()
{
var result = Parse(indata);
Assert.IsNotNull(result);
//Test serialize the result to json
string jsonString = JsonConvert.SerializeObject(result);
Console.WriteLine(jsonString);
}
private DataModel Parse(string indata)
{
if (string.IsNullOrEmpty(indata))
{
throw new ArgumentNullException(nameof(indata));
}
var lines = indata.Split("\r\n").ToList();
if (lines == null || lines.Count < 1)
{
throw new ArgumentNullException(nameof(indata));
}
var result = new DataModel();
result.Date = ParseDate(lines);
result.MachineId = ParseMachineId(lines);
result.UserId = ParseUserId(lines);
result.Type = ParseType(lines);
result.Notes = ParseNotes(lines);
result.Total = ParseTotal(lines);
result.TotalAmount = ParseTotalAmount(lines);
return result;
}
private IList<Note> ParseNotes(List<string> lines)
{
var titleLineIndex = GetTitleLineIndex(lines);
var closestDashLineIndex = GetClosestDashedLineNumber(lines, titleLineIndex);
var result = new List<Note>();
for (int i = titleLineIndex + 1; i < closestDashLineIndex; i++)
{
if (!string.IsNullOrEmpty(lines[i]))
{
var dataItems = lines[i].Split(" ");
var dataModel = new Note();
dataModel.This = dataItems.Length > 0 ? ToInt32(dataItems[0]) : 0;
dataModel.That = dataItems.Length > 1 ? ToInt32(dataItems[1]) : 0;
dataModel.Total = dataItems.Length > 2 ? ToInt32(dataItems[2]) : 0;
result.Add(dataModel);
}
}
return result;
}
private string ParseDate(List<string> lines)
{
var dateValue = GetLineValue(lines, "Date :");
try
{
var date = DateTime.ParseExact(dateValue, "HH:mm dd/MM/yyyy", CultureInfo.InvariantCulture, DateTimeStyles.None);
return date.ToString("HH:mmddMMyyyy");
}
catch
{
return string.Empty;
}
}
private string ParseMachineId(List<string> lines)
{
var identifier = "Machine SN :";
return GetLineValue(lines, identifier);
}
private string ParseUserId(List<string> lines)
{
var identifier = "User ID :";
return GetLineValue(lines, identifier);
}
private string ParseType(List<string> lines)
{
var identifier = "Type:";
return GetLineValue(lines, identifier);
}
private int ParseTotal(List<string> lines)
{
var total = lines[lines.Count - 5];
if (!string.IsNullOrEmpty(total))
{
var values = total.Split(" ");
return values.Length > 0 ? ToInt32(values[0]) : 0;
}
return 0;
}
private int ParseTotalAmount(List<string> lines)
{
var totalAmount = lines[lines.Count - 2];
return ToInt32(totalAmount);
}
private string GetLineValue(List<string> lines, string identifier)
{
var line = lines.FirstOrDefault(x => x.StartsWith(identifier));
if (string.IsNullOrEmpty(line))
{
return string.Empty;
}
else
{
return line.Replace(identifier, string.Empty).Trim();
}
}
private int GetTitleLineIndex(List<string> lines)
{
string titleLine = "This That Total";
return lines.ToList().IndexOf(titleLine);
}
private int GetClosestDashedLineNumber(List<string> lines, int titleLineIndex)
{
string dashLine = "------------------------------------------";
var closestDashLineIndex = lines.FindIndex(titleLineIndex, x => x == dashLine);
return closestDashLineIndex;
}
private int ToInt32(string value)
{
try
{
return int.Parse(value);
}
catch (Exception ex)
{
return 0;
}
}
public class DataModel
{
[JsonProperty(PropertyName = "date")]
public string Date { get; set; }
[JsonProperty(PropertyName = "machineId")]
public string MachineId { get; set; }
[JsonProperty(PropertyName = "userId")]
public string UserId { get; set; }
[JsonProperty(PropertyName = "type")]
public string Type { get; set; }
[JsonProperty(PropertyName = "notes")]
public IList<Note> Notes { get; set; }
[JsonProperty(PropertyName = "total")]
public int Total { get; set; }
[JsonProperty(PropertyName = "totalAmount")]
public int TotalAmount { get; set; }
}
public class Note
{
[JsonProperty(PropertyName = "this")]
public int This { get; set; }
[JsonProperty(PropertyName = "that")]
public int That { get; set; }
[JsonProperty(PropertyName = "total")]
public int Total { get; set; }
}
const string indata = @"
------------------------------------------
Date : 11:33 25/07/2022
Machine SN : 1234509385_9
User ID : 1-Emplo
------------------------------------------
------------ Value People Total -----------
Type: Data
------------------------------------------
This That Total
7 25 125
53 32 320
87 25 500
95 20 1000
110 35 3500
------------------------------------------
Total
137 5445
------------------------------------------
Total Amount
5445
-------------------------------------------";
}
}
Run the test, get result as below:
{
"date": "11:3325072022",
"machineId": "1234509385_9",
"userId": "1-Emplo",
"type": "Data",
"notes": [
{
"this": 7,
"that": 25,
"total": 125
},
{
"this": 53,
"that": 32,
"total": 320
},
{
"this": 87,
"that": 25,
"total": 500
},
{
"this": 95,
"that": 20,
"total": 1000
},
{
"this": 110,
"that": 35,
"total": 3500
}
],
"total": 137,
"totalAmount": 5445
}
If right, please Accept.
Enjoy programming!!!