nested Json to C# classes or function

How would I deserialize this json snippet?

{"OBITS/BTS":{"timestamp":1518205774653,"asks":[],"bids":[]},"MSCN/RUR":{"timestamp":1518205774654,"asks":[],"bids":[]}

Open in new window

CAMPzxzxDeathzxzxAsked:
Who is Participating?
 
it_saigeConnect With a Mentor DeveloperCommented:
Basically this is the same as ste5an's implementation, just using Lists instead of Arrays and Properties instead of Fields:
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Numerics;

namespace EE_Q29083283
{
    class Program
    {
        static string json = "{\"OBITS/BTS\":{\"timestamp\":1518205774653,\"asks\":[],\"bids\":[]},\"MSCN/RUR\":{\"timestamp\":1518205774654,\"asks\":[],\"bids\":[]}}";
        static void Main(string[] args)
        {
            var data = JsonConvert.DeserializeObject<Outer>(json);
            Console.WriteLine("OBITS/BTS - TimeStamp: {0}; Asks: {1}; Bids: {2}", data.ObitsBts.Timestamp, data.ObitsBts.Asks.Count, data.ObitsBts.Bids.Count);
            Console.WriteLine("MSCN/RUR - TimeStamp: {0}; Asks: {1}; Bids: {2}", data.MscnRur.Timestamp, data.MscnRur.Asks.Count, data.MscnRur.Bids.Count);
            Console.ReadLine();
        }
    }

    class Outer
    {
        [JsonProperty(PropertyName = "OBITS/BTS")]
        public Inner ObitsBts { get; set; }
        [JsonProperty(PropertyName = "MSCN/RUR")]
        public Inner MscnRur { get; set; }
    }

    class Inner
    {
        public BigInteger Timestamp { get; set; } 
        public List<int> Asks { get; set; }
        public List<int> Bids { get; set; }
    }
}

Open in new window

Produces the following output -Capture.PNG
-saige-
0
 
ste5anSenior DeveloperCommented:
Something like this should do it:

class inner 
{
  bigint timestamp;
  int[] asks;
  int[] bids;
}

class outer
{
  inner ObitsBts;
  inner MscnRur;
}

Open in new window

0
 
CAMPzxzxDeathzxzxAuthor Commented:
Can you show me usage?  I tried to implement as shown without success.
0
 
CAMPzxzxDeathzxzxAuthor Commented:
Thanks
0
 
zephyr_hex (Megan)DeveloperCommented:
The JSON you gave as an example is invalid.  It should look something like:

{"data": [
                        { "type" : "OBITS/BTS", "timestamp":"1518205774653","asks":"[]","bids":"[]" }, 
                        {  "type" : "MSCN/RUR", "timestamp":"1518205774654","asks":"[]","bids":"[]" }
                        ]
                        }

Open in new window


Which would produce:
 public class Datum
    {
        public string type { get; set; }
        public string timestamp { get; set; }
        public string asks { get; set; }
        public string bids { get; set; }
    }

    public class Example
    {
        public IList<Datum> data { get; set; }
    }

Open in new window


BTW, there are online tools that will convert JSON to C# classes.  One such tool:  https://jsonutils.com/
0
All Courses

From novice to tech pro — start learning today.