I have a console application where I want to read commands from an input file and write the corresponding output to another file. One of my example commands looks like this:
[{"command":"addItem","payload":{"id":1,"catId":1,"sId":1,"price":1.2,"quantity":1}}]
I am trying to deserialize this command using System.Text.Json. Here is the relevant code snippet:
public class Input
{
public string Command { get; set; }
public object Payload { get; set; }
}
List<Input> command = JsonSerializer.Deserialize<List<Input>>(commandLine);
I chose to use object for the Payload property because it can vary based on the command type. However, I am facing an issue where the deserialization always returns a null value during debugging.
Additionally, I am reading the input file with the following code:
string inputFilePath = Path.Combine(Directory.GetCurrentDirectory(), "input.txt");
if (!File.Exists(inputFilePath))
{
Console.WriteLine($"Not found: {inputFilePath}");
return;
}
string jsonContent = await File.ReadAllTextAsync(inputFilePath);
List<Input> commands = JsonSerializer.Deserialize<List<Input>(jsonContent);
foreach (var commandLine in commands)
{
await ExecuteCommand(commandLine);
}
I implemented this method to facilitate debugging, but I would also like to know how to read the input file path directly from the console instead.
Could someone help me with both deserialization issues and reading the input file path from the console?
2
Answers
FOr that I would suggest using
dynamic
type. To correctly handle deserialization, you’d need to useNewtonsoft
nuget:.NET fiddle
}
The above solution worked for me, hope it helps you