CAMPzxzxDeathzxzx
asked on
Dynamically parse nested JSon data to C# class
Is there a way to make to rewrite this dynamically? There are over 500 "public inner" / "[JsonProperty(PropertyNam e =" in this Json data.
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; }
}
ASKER
I'm comfortable with C# and SQL but not JSON. I know that this data is not valid...
here is a snippet:
so now I'm attempting this...
here is a snippet:
{"OBITS/BTS":{"timestamp":1518205774653,"asks":[],"bids":[]},"MSCN/RUR":{"timestamp":1518205774654,"asks":[],"bids":[]}
so now I'm attempting this...
json = json.Substring(json.IndexOf("[") + 1);
json = json.Substring(0, json.LastIndexOf("]"));
var rootObjects = JsonConvert.DeserializeObject<RootObject>(json);
ASKER
HttpResponseMessage message = httpClient.GetAsync(uri).Result;
var inter = message.Content.ReadAsStringAsync();
string obj = JsonConvert.DeserializeObject(inter.Result).ToString();
Get's me this..
The original question shows a class structure that works..
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; }
}
But I'm looking to parse these dynamically.
ASKER
I got it into a data form I can use!
HttpResponseMessage message = httpClient.GetAsync(uri).Result;
var inter = message.Content.ReadAsStringAsync();
string obj = JsonConvert.DeserializeObject(inter.Result).ToString();
var x = (JsonConvert.DeserializeObject<IDictionary<string, object>>(obj));
ASKER CERTIFIED SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
ASKER
Thanks
Did you manage to have a look into dynamic keyword in C#? If not, please do.
It may take a while for me to write a sample code, so posting this just to give you a head-start.
Do let me know if further help is required. Also if you could post complex enough json to try with, please.