Skip to content

Commit

Permalink
Table from JSon string constructor
Browse files Browse the repository at this point in the history
  • Loading branch information
PiotrNestor committed Jul 1, 2024
1 parent a234a90 commit a4aaf39
Showing 1 changed file with 25 additions and 0 deletions.
25 changes: 25 additions & 0 deletions Gauge.CSharp.Lib/Table.cs
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
* See LICENSE.txt in the project root for license information.
*----------------------------------------------------------------*/
using System;
using System.Reflection;
using System.Runtime.Serialization.Json;
using System.IO;
using System.Text;
Expand Down Expand Up @@ -34,6 +35,30 @@ public Table(List<string> headers)
_tableRows = new List<TableRow>();
}

/// <summary>
/// Creates a new Table type from JSON string
/// </summary>
/// <param name="asJson">A JSON string representing the Table object.</param>
public Table(string asJSon)
{
var serializer = new DataContractJsonSerializer(typeof(Table));
using (var ms = new MemoryStream(Encoding.UTF8.GetBytes(asJSon)))
{
var deserializedTable = serializer.ReadObject(ms) as Table;
if (deserializedTable != null)
{
// Use LINQ with reflection to copy properties
typeof(Table).GetFields(BindingFlags.NonPublic | BindingFlags.Instance)
.ToList()
.ForEach(field => field.SetValue(this, field.GetValue(deserializedTable)));
}
else
{
throw new ArgumentException("Invalid JSON string for Table deserialization.");
}
}
}

public Table FromJSon(string asJSon)
{
var serializer = new DataContractJsonSerializer(typeof(Table));
Expand Down

0 comments on commit a4aaf39

Please sign in to comment.