0

I can't quite seem to work out how I would deserialize this specific array in c# (from a string!) to a class

  [
    [
      "PrimaryContact", 
      "=", 
      "Amy R"
    ], 
    "and", 
    [
      "SecondaryContact", 
      "=", 
      "Steven G"
    ],
    "and",
    [
      "ThirdContact",
      "=",
      "Rachel S"
    ]
  ]

Specifically it's the middle section that is throwing me, in this case it is "and". It isn't always just three objects, there could an unlimited amount of objects, with an "and" inbetween each of them.

dcastro
  • 66,540
  • 21
  • 145
  • 155
wh-dev
  • 537
  • 5
  • 18

2 Answers2

2

You could deserialize it into a list of objects:

List<object> items = new JavaScriptSerializer().Deserialize<List<object>>(json);

Now every other object will be an Object[] (containing objects that are String), the ones in between String.

Guffa
  • 687,336
  • 108
  • 737
  • 1,005
  • 1
    Thank you, this works! Bit of a hacky solution so I might go to DevExpress to ask them to 'grow a brain' courtesy of @dcastro! – wh-dev Jan 16 '15 at 15:32
1

Using Json.NET, parse everything into a JArray, then filter out tokens at even indexes, and then convert each into a List<string>.

You'll end up with a collection of List<string>, where each list contains 3 elements, e.g., "PrimaryContact", "=" and "Amy R"

var array = JArray.Parse(json);

IEnumerable<List<string>> result = array.Where((token, index) => index%2 == 0)
                                        .Select(token => token.ToObject<List<string>>());

This worked for me using your input

dcastro
  • 66,540
  • 21
  • 145
  • 155
  • This removes the `"and"` keyword, which is essential. There are other instances where this keyword *could* be `"or"` – wh-dev Jan 16 '15 at 15:18
  • I thought you didn't need it.. So whats the type of the object you want to end up with? It seems like you want a `List` as suggested by @Guffa then – dcastro Jan 16 '15 at 15:20