skip to Main Content

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


  1. FOr that I would suggest using dynamic type. To correctly handle deserialization, you’d need to use Newtonsoft nuget:

    using Newtonsoft.Json;
    
    var rawJson = @"[{""command"":""addItem"",""payload"":{""id"":1,""catId"":1,""sId"":1,""price"":1.2,""quantity"":1}}]";
    
    var deserialized = JsonConvert.DeserializeObject<dynamic>(rawJson);
    
    Console.WriteLine(deserialized[0].command);
    Console.WriteLine(deserialized[0].payload.id);
    Console.WriteLine(deserialized[0].payload.catId);
    Console.WriteLine(deserialized[0].payload.sId);
    Console.WriteLine(deserialized[0].payload.price);
    Console.WriteLine(deserialized[0].payload.quantity);
    

    .NET fiddle

    Login or Signup to reply.
  2. using System;
    using System.Collections.Generic;
    using System.IO;
    using Newtonsoft.Json;
    
    namespace JsonDeserializer
    {
    public class Input
    {
        public string Command { get; set; }
        public dynamic Payload { get; set; }
    }
    
    class Program
    {
        static void Main(string[] args)
        {
            
            Console.WriteLine("Please enter the path to the JSON file:");
            string filePath = Console.ReadLine();
    
            // Check if the file exists
            if (!File.Exists(filePath))
            {
                Console.WriteLine("The file path entered is invalid or the file does not exist.");
                return;
            }
    
            try
            {
                // Read the file content
                string jsonContent = File.ReadAllText(filePath);
    
                // Deserialize the JSON into a list of Input objects
                List<Input> inputs = JsonConvert.DeserializeObject<List<Input>>(jsonContent);
    
                // Output the results
                foreach (var input in inputs)
                {
                    Console.WriteLine($"Command: {input.Command}");
                    Console.WriteLine($"Payload: {input.Payload}");
                    Console.WriteLine();
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine($"An error occurred while processing the file: {ex.Message}");
            }
        }
    }
    

    }

    The above solution worked for me, hope it helps you

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search