-3

How can I deserialize a Json Array of Lists?

Example:

[
  [
    "id",
    "date",
    "time",
    "start_time",
    "end_time",
    "sc_name"
  ],
  [
    121329387,
    "2022-05-07",
    null,
    null,
    null
  ],
  [
    123863076,
    "2022-12-05",
    null,
    null,
    null
  ]
]

How can I convert the above string to List type

  • 1
    What "LIst type"? – Tim Schmelter Jul 11 '22 at 10:47
  • You would need to write some kind of parser. To C# that string is just a string. There's no list of any kind. – Jeroen Mostert Jul 11 '22 at 10:51
  • Missing code to show what you tried so far. Try searching for tokenizing and regex. – Danny Varod Jul 11 '22 at 10:51
  • @JeroenMostert - Well, to be fair, it's a list of `char`. – Enigmativity Jul 11 '22 at 11:03
  • 2
    @Enigmativity: OK, if we *really* want to pick nits here, technically it's at best an `IEnumerable`. (I guess `IReadOnlyList` came too late to the party to be considered for addition, while implementing `IList` would have been too burdensome/confusing since strings are immutable.) It is a "list" in the abstract sense, I suppose. In any case none of this is helpful to the OP. :P – Jeroen Mostert Jul 11 '22 at 11:09
  • Lists of Lists are usually symptoms of an incorrect object model. Consider [creating a list of a class that implements your model behavior](https://stackoverflow.com/questions/21692193/why-not-inherit-from-listt). – Dour High Arch Jul 11 '22 at 18:23

1 Answers1

1

If "List type" means List<List<int>>, you can Split two times:

  1. By ][ to have lines
  2. By , to have integer numbers

Code:

string a = "[1,2,3][1,3,4][1,1,1]";

List<List<int>> result = a
  .Split("][")
  .Select(line => line
     .Trim(']', '[')
     .Split(',')
     .Select(number => int.Parse(number))
     .ToList())
  .ToList();

To obtain separate list, just address result with the requied index:

// {1, 3, 4}
List<int> secondLine = result[1];
Dmitry Bychenko
  • 180,369
  • 20
  • 160
  • 215