如果密钥不同,我如何反序列化JSON文件,密钥从key1到keyN?当我使用python它很容易,
import pandas as pd
myJson = pd.json.loads(json)
刚刚使用了两行代码,但是当我使用C#时,对我来说非常难。谢谢。
public class Rootobject
{
public Key1 key1 { get; set; }
public Key2 key2 { get; set; }
public Key3 key3 { get; set; }
}
2.现在我使用下面的方法,但我仍然认为它不像python那么简单。
JObject items = JObject.Parse(json);
foreach(var item in items)
{
JObject v = JObject.Parse(item.Value.ToString());
foreach(KeyValuePair<string, JToken> property in v)
{ //do something}
}
json string:
{
"key1":
{
"id":1,
"name":"i",
"AllocationInfo":
{
"State":"Init",
"Name":"test",
"TModel":
{
"Name":"test2",
"key":"1232445",
"v":{
"id":"090",
"Name":"tom"
}
}
}
},
"key2":
{
"id":1,
"name":"i",
"AllocationInfo":
{
"State":"Init",
"Name":"test",
"TModel":
{
"Name":"test2",
"key":"1232445",
"v":{
"id":"090",
"Name":"tom"
}
}
}
},
"key3":
{
"id":1,
"name":"i",
"AllocationInfo":
{
"State":"Init",
"Name":"test",
"TModel":
{
"Name":"test2",
"key":"1232445",
"v": {
"id":"090",
"Name":"tom",
"D":{"id":"7890"}
}
}
}
}
}
答案 0 :(得分:1)
使用粘贴特殊粘贴时粘贴了整个json。但我认为您只想为所有keyN对象生成一个类。然后,您可以使用Newtonsoft将json反序列化为列表。
var myKeys = Newtonsoft.Json.JsonConvert.DeserializeObject<List<KeyN>>(json);
答案 1 :(得分:1)
使用DeserializeObject并从中获取字典:
var r = JsonConvert.DeserializeObject<Dictionary<string, Key>>(txt);
宣布你的课程:
public class Key
{
public int id { get; set; }
public string name { get; set; }
public AllocationInfo AllocationInfo { get; set; }
}
public class AllocationInfo
{
public string State { get; set; }
public string Name { get; set; }
public TModel TModel { get; set; }
}
public class TModel
{
public string Name { get; set; }
public string key { get; set; }
public v v { get; set; }
}
public class v
{
public string id { get; set; }
public string name { get; set; }
}