Reputation: 29
My application receives 2 JSON. One of which is:
{
"topics": {
"test1": {
"topic": "test1",
"partitions": {
"0": {
"partition": 0,
"next_offset": 8265537,
"app_offset": 8265537,
"stored_offset": 8265537,
"commited_offset": 8265537,
"committed_offset": 8265537,
"eof_offset": 8265537,
"lo_offset": 8261962,
"hi_offset": 8265537,
"consumer_lag": 0
},
"1": {
"partition": 1,
"next_offset": 9207622,
"app_offset": 9207622,
"stored_offset": 9207622,
"commited_offset": 9207622,
"committed_offset": 9207622,
"eof_offset": 9207622,
"lo_offset": 9203938,
"hi_offset": 9207622,
"consumer_lag": 0
},
"2": {
"partition": 2,
"next_offset": 7954425,
"app_offset": 7954425,
"stored_offset": 7954425,
"commited_offset": 7954425,
"committed_offset": 7954425,
"eof_offset": 7954425,
"lo_offset": 7950785,
"hi_offset": 7954425,
"consumer_lag": 0
}
}
}
}
}
And the other is test2 with "topic" as "test2". And the topic name differentiates both the JSON.
One way I basically converted it into dynamic object and loop through the JSON. But I want to create one common class for both JSON to convert it into. My only confusion is how can create a generic class to deserialize both the JSON.
Because right now I am creating two classes like :
public class Root
{
public Topics topics { get; set; }
}
public class Topics
{
public Test1 test1 { get; set; }
}
public class Test1
{
public string topic { get; set; }
public Partitions partitions { get; set; }
}
And same way for test2.
Any help?
Upvotes: 0
Views: 154
Reputation: 1
List Sample: - JSON object & class object like below:
{
"topics":[{
"topic":"test1",
"partition":{...}
},{
"topic":"test2",
"partition":{...}
}]
}
class Root
{
public List<Topics> topics { get; set; }
}
class Topics
{
public string topic { get; set; }
public Partitions partitions { get; set; }
}
Specify Sample: - JSON object & class object like below:
{
"topics":{
"test1":{
"topic":"test1",
"partition":{...}
},
"test2":{
"topic":"test2",
"partition":{...}
}]
}
class Root
{
public Test topics{ get; set; }
}
class Test{
public Topics test1{get;set;}
public Topics test2{get;set;}
}
class Topics
{
public string topic { get; set; }
public Partitions partitions { get; set; }
}
Upvotes: 0
Reputation: 119146
I'd suggest using Dictionary<>
types for keys that will change like the test1
value and the partition numbers. For example, something like this should work well:
public class Root
{
public Dictionary<string, Test> Topics { get; set; }
}
public class Test
{
public string Topic { get; set; }
public Dictionary<int, Partition> Partitions { get; set; }
}
public class Partition
{
[JsonProperty("partition")]
public int PartitionNo { get; set; }
[JsonProperty("next_offset")]
public int NextOffset { get; set; }
// etc...
}
And deserialise with:
var result = JsonConvert.DeserializeObject<Root>(Json);
Upvotes: 1