I receive from tcpstream message with this format :
["bilbo,1,0,0,0,0,1,2022-11-21 19:06:10","mangnoune,1,0,0,0,0,2,2022-11-21 19:08:18"]
["string, int, int, float, float, float, int, DateTime","next array pattern"]
I want to deserialize this to:
class player
{
string name;
int level;
int xp;
float x;
float y;
float z;
int status;
Datetime lastPlayed;
}
In this example there are 2 players objects.
CodePudding user response:
An easy option is to use JsonSerializer
first to obtain a list of player strings and then parse each string individually.
I am using an extension method here which allows to deconstruct an array with 8 values, but that's not necessary, you can just as well use the array indices directly.
From that point onward it's just about converting string
to int
which you can do using the Convert
class and about parsing a Date which you can do using DateTime.Parse()
.
This implementation will throw exceptions for unexpected data.
using System.Text;
using System.Text.Json;
namespace Program
{
record Player(string Name, int Level, int Xp, float X, float Y, float Z, int Status, DateTime LastPlayed);
class Program
{
public static async Task Main(string[] args)
{
var json = @"[""bilbo,1,0,0,0,0,1,2022-11-21 19:06:10"",""mangnoune,1,0,0,0,0,2,2022-11-21 19:08:18""]";
var playerStrings = await JsonSerializer.DeserializeAsync<List<string>>(new MemoryStream(Encoding.UTF8.GetBytes(json)));
var parsedPlayers = playerStrings
.Select(playerString => ParsePlayer(playerString))
.ToList();
foreach (var player in parsedPlayers)
{
Console.WriteLine(player);
}
}
public static Player ParsePlayer(string playerString)
{
var (name, level, xp, x, y, z, status, lastPlayed) = playerString.Split(",");
return new Player
(
Name: name,
Level: Convert.ToInt32(level),
Xp: Convert.ToInt32(xp),
X: Convert.ToInt32(x),
Y: Convert.ToInt32(y),
Z: Convert.ToInt32(z),
Status: Convert.ToInt32(status),
LastPlayed: DateTime.Parse(lastPlayed)
);
}
}
static class ArrayExtensions
{
public static void Deconstruct<T>(this T[] srcArray, out T a0, out T a1, out T a2, out T a3, out T a4, out T a5, out T a6, out T a7)
{
if (srcArray == null || srcArray.Length < 8)
throw new ArgumentException(nameof(srcArray));
a0 = srcArray[0];
a1 = srcArray[1];
a2 = srcArray[2];
a3 = srcArray[3];
a4 = srcArray[4];
a5 = srcArray[5];
a6 = srcArray[6];
a7 = srcArray[7];
}
}
}
Expected output:
Player { Name = bilbo, Level = 1, Xp = 0, X = 0, Y = 0, Z = 0, Status = 1, LastPlayed = 21/11/2022 19:06:10 }
Player { Name = mangnoune, Level = 1, Xp = 0, X = 0, Y = 0, Z = 0, Status = 2, LastPlayed = 21/11/2022 19:08:18 }