我有这样的json
{
"result": "success",
"response_code": 200,
"message": "",
"collection": {
"<channel_id>": {
"<category_id>": {
"id_category": "<category_id>",
"name": "<category>",
"date_created": "<date_tagged>"
},
"<category_id>": {
"id_category": "<category_id>",
"name": "<category>",
"date_created": "<date_tagged>"
}
}
}
}
哪个channel_id和category_id不是固定名称。如何在C#上反序列化?
答案 0 :(得分:3)
假设其他所有内容都已修复,您可以尝试按以下方式对其进行建模:
public class MyJsonClass
{
public String Result { get; set; }
public int Response_Code { get; set; }
public String Message { get; set; }
public Dictionary<String, Dictionary<String, JsonCategoryDescription>>
Collection { get; set; }
}
public class JsonCategoryDescription
{
public String Id_Category { get; set; }
public String Name { get; set; }
public String Date_Created { get; set; }
}
然后按如下方式对其进行反序列化(System.Web.Script.Serialization
命名空间):
var result = new JavaScriptSerializer().Deserialize<MyJsonClass>(myJsonString);
您可以访问特定字段,如下所示:
result.Collection[SOME_CHANNEL_ID][SOME_CATEGORY_ID].Name = "XXX";
答案 1 :(得分:0)
如果使用Dynamic而不是静态类型,则可以使用JSON文件的变量模式。这是一个工作控制台程序:
class Program
{
static void Main(string[] args)
{
var json = File.ReadAllText("file.json");
dynamic obj = JObject.Parse(json);
Console.WriteLine(obj.collection.channel_id);
}
}