0

I have a case where my JSON-structure is as follows:

{
  offset: 20,
  records: 
    [ 
      {
        key1:val, 
        key2:val, 
        key3:val
      }, 
      {
        key1:val, 
        key2:val, 
        key3:val
      }
    ]
}

I want to get this to the point where I can access the records array as an array containing Dictionaries (where the "key value" is the key and "val" is the value). I've tried using a Dto class to match the JSON data but I fall short on the last level.

public class Root
{
    public int next_offset { get; set; }
    public List<Records>  records { get; set; }
}

public class Records
{
    public string key1 { get; set; }
    public string key2 { get; set; }
    public string key3 { get; set; }
}

But since I need the "keys" as well, not just their values this does not work perfect either.

Please help me to sort out this issue.

Sir Rufo
  • 18,395
  • 2
  • 39
  • 73
Erik
  • 13
  • 6

2 Answers2

0

Have you tried the json.net library.It provides what you are looking for.You can download it as a nuget package.

PS:You can paste the JSON as classes in Visual Studio enter image description here

ashish
  • 2,028
  • 1
  • 10
  • 6
  • I use Newtonsoft for my other serializing, but I haven't got that to work quite as I want it to. Do you have any example of how I should implement it in my case? – Erik Jun 30 '17 at 12:07
0

Is this what you're looking for? (Also see .net fiddle here: https://dotnetfiddle.net/Q4zyvy )

using System;
using System.Collections.Generic;
using Newtonsoft.Json;

public class Root
{
    public int Offset { get; set; }
    public List<Dictionary<string, string>> Records { get; set; }
}

public class Program
{
    public static void Main()
    {
        var asDictionary = JsonConvert.DeserializeObject<Root>(@"{

        offset: 20,
        records:[
            {
                key1: ""value 1"",
                key2: ""value 2"",
                key3: ""value 3""
            },
            {
                key1: ""value 4"",
                key2: ""value 5"",
                key3: ""value 6""
            }           
        ]}");

        Console.WriteLine("Offset: {0}", asDictionary.Offset);
        foreach( var record in asDictionary.Records )
        {
            Console.WriteLine("-----");
            foreach(var pair in record)
            {
                Console.WriteLine("{0} = {1}", pair.Key, pair.Value);
            }
        }
    }
}
deepcode.co.uk
  • 1,464
  • 1
  • 14
  • 22