我的应用程序收到2个JSON。其中之一是:
{
"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
}
}
}
}
}
另一个是test2,其中“ topic”为“ test2”。主题名称区分了JSON和JSON。
我基本上将其转换为动态对象并通过JSON循环的一种方式。 但是我想为两个JSON创建一个通用类以将其转换为。我唯一的困惑是如何创建一个通用类来反序列化JSON。
因为现在我要创建两个类:
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; }
}
与test2相同。
有帮助吗?
答案 0 :(得分:1)
我建议将Dictionary<>
类型的键用于更改,例如test1
值和分区号。例如,类似这样的方法应该可以很好地工作:
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...
}
并反序列化:
var result = JsonConvert.DeserializeObject<Root>(Json);
答案 1 :(得分:0)
列出示例: -JSON对象和类对象,如下所示:
{
"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; }
}
指定示例: -JSON对象和类对象,如下所示:
{
"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; }
}