c# - 如何反序列化具有变量类名的字符串
问题描述
我需要反序列化一个包含一系列表的 JSON 字符串,但其中一个类仅包含一个字符串并且不包含标题。所以我不知道如何只用一个字符串来指定类。
这是一个简化的示例:
"tables" : {
"tableId1" : {
"name" : "Name_Of_The_Table"
},
"tableId2" : {
"name" : "Name_Of_The_Table"
},
...
}
实际上,大约有 100 多个不同的表,每个表都有单独的名称。
我用来反序列化的类如下:
public class jsonBaseClass
{
public List<tableClass> tables {get; set;}
}
public class tableClass
{
public string name {get; set;}
}
所以我遇到的问题是我需要将 tableId 也包含在 tableClass 中,但我不知道如何包含它。
有人有想法吗?
解决方案
您可以使用JsonProperty属性来获得所需的结果,这是一个示例:
public class Program
{
public static void Main(string[] args)
{
string data = @"{
'tables' : {
'tableId1' : {
'name' : 'Name_Of_The_Table'
},
'tableId2' : {
'name' : 'Name_Of_The_Table'
}
}
}";
RootObject deserializedObject = JsonConvert.DeserializeObject<RootObject>(data);
Console.WriteLine(JsonConvert.SerializeObject(deserializedObject, Formatting.Indented));
}
}
public class RootObject
{
[JsonProperty("tables")]
public TableCollection Tables { get; set; }
}
public class TableCollection
{
[JsonProperty("tableId1")]
public Table1 Table1 { get; set; }
[JsonProperty("tableId2")]
public Table2 Table2 { get; set; }
}
public class Table1
{
[JsonProperty("name")]
public string Name { get; set; }
}
public class Table2
{
[JsonProperty("name")]
public string Name { get; set; }
}
输出:
{
"tables": {
"tableId1": {
"name": "Name_Of_The_Table"
},
"tableId2": {
"name": "Name_Of_The_Table"
}
}
}
或者,如果属性名称未知,则使用 JSON.NET LINQ。
public class Program
{
public static void Main(string[] args)
{
string data = @"{
'tables' : {
'tableId1' : {
'name' : 'Table1'
},
'tableId2' : {
'name' : 'Table2'
}
}
}";
JObject deserializedObject = JsonConvert.DeserializeObject<JObject>(data);
List<JObject> tableObjectList = deserializedObject["tables"]
.Cast<JProperty>()
.Select(x => x.Value)
.Cast<JObject>()
.ToList();
List<string> tableIDList = deserializedObject["tables"]
.Cast<JProperty>()
.Select(x => x.Name)
.ToList();
Console.WriteLine(JsonConvert.SerializeObject(tableObjectList, Formatting.Indented));
Console.WriteLine(JsonConvert.SerializeObject(tableIDList, Formatting.Indented));
}
}
输出:
[
{
"name": "Table1"
},
{
"name": "Table2"
}
]
[
"tableId1",
"tableId2"
]
推荐阅读
- regex - 从一个文件中提取数据并保存到另一个文件
- plsql - 如何在 PL/SQL 过程中执行“DELETE FROM ... WHERER .... IN VARIABLE”
- rdf - 将一个复杂的句子翻译成一组 SPO 三元组 (RDF)(可能带有具体化)
- javascript - React Native:无法读取未定义的属性“isConnected”(检测应用程序连接)
- sql-server - 从有序表创建层次结构
- javascript - 当具有多个系列的图表与具有单个系列的图表链接时,echarts.connect 被破坏
- matlab - 如何从声压 (Pa) 中提取声压级 (dB) 并绘制它与时间的关系图?
- node.js - Postgres:一对多关系的复杂多次更新查询
- directx - warning X4000: use of potentially uninitialized variable
- python - 将像素校准为真实世界单位