0

Given:
Visual Studio 2022 Console Application

I'm trying to pass a json string value through console parameter and am having trouble deserializing it. I'm using Paste Special to create the json classes from a json sample.

[
  {
    "CustomerId": 1,
    "CustomerName": "Test1"
  },
  {
    "CustomerId": 2,
    "CustomerName": "Test2"
  }
]

Here's my launchSettings.json file

{
  "profiles": {
    "ConsoleApp4": {
      "commandName": "Project",
      "commandLineArgs": "[ { \"CustomerId\": 1, \"CustomerName\": \"Test1\" }, { \"CustomerId\": 2, \"CustomerName\": \"Test2\" } ]"
    }
  }
}

Here's my program.cs file

namespace ConsoleApp4
{
    internal class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("Hello, World!");

            var result = System.Text.Json.JsonSerializer.Deserialize<Rootobject>(args[0]);
        }
    }

    public class Rootobject
    {
        public Class1[] Property1 { get; set; }
    }

    public class Class1
    {
        public int CustomerId { get; set; }
        public string CustomerName { get; set; }
    }
}

Here's the error I'm getting:

The JSON value could not be converted to ConsoleApp4.Rootobject. Path: $ | LineNumber: 0 | BytePositionInLine: 1.
Rod
  • 14,529
  • 31
  • 118
  • 230

1 Answers1

2

Your JSON starts with a [, indicating that it's an array, not an object. You don't need Rootobject at all, but you should deserialize to List<Class1>.

Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194