c#反序列化JSON



我在反序列化json对象时遇到问题,因为它不包含数组。

json字符串的示例:

 {
  "Data": {
    "A1": {
      "name": "",
      "code": "",      
      "type": ""
    },
    "A2": {
     "name": "",
      "code": "",      
      "type": ""
    },
    "A3": {
      "name": "",
      "code": "",      
      "type": ""
    }
  }
}

这是我的代码,json字符串将从文件中读取,不能更改。

var json = "{"Data":{"A1":{"name":"","code":"","type":""},"A2":{"name":"","code":"","type":""},"A3":{"name":"","code":"","type":""}}}";
var jobject = JsonConvert.DeserializeObject<DataContainer>(json);

public class Data
{
    public string name { get; set; }
    public string code { get; set; }            
    public string type { get; set; }
}
public class DataContainer
{
    public List<Data> Data { get; set; }
}

我设法做到这一点的唯一方法是通过改变json使用像下面的例子一样的数组,但我希望解决这个问题,而不必改变json文件的格式。

{
  "Data": [
    {
      "name": "",
      "code": "",      
      "type": ""
    },
    {
     "name": "",
      "code": "",      
      "type": ""
    },
    {
      "name": "",
      "code": "",      
      "type": ""
    }
  ]
}

谢谢

json包含一个Data对象,其中包含三个不同的对象:A1, A2, A3。

所以我认为你需要实现三个不同的类,和一个容器
public class A1
{
    public string name { get; set; }
    public string code { get; set; }
    public string type { get; set; }
}
public class A2
{
    public string name { get; set; }
    public string code { get; set; }
    public string type { get; set; }
}
public class A3
{
    public string name { get; set; }
    public string code { get; set; }
    public string type { get; set; }
}
public class Data
{
    public A1 A1 { get; set; }
    public A2 A2 { get; set; }
    public A3 A3 { get; set; }
}

我创建了2个类,并像这样手动反序列化json对象:

class Program
{
    static void Main(string[] args)
    {
        var json = "{"Data":{"A1":{"name":"","code":"","type":""},"A2":{"name":"","code":"","type":""},"A3":{"name":"","code":"","type":""}}}";
        var data = (JsonConvert.DeserializeObject(json) as Newtonsoft.Json.Linq.JObject).First.First;
        List<DataItem> list = new List<DataItem>();
        foreach (var item in data.ToList())
        {
            list.Add(new DataItem()
            {
                Name = ((Newtonsoft.Json.Linq.JProperty)(item)).Name,
                A = JsonConvert.DeserializeObject<A>(item.First.ToString())
            });
        }
    }
    class DataItem
    {
        public string Name { get; set; } //A1, A2, A3 ....
        public A A { get; set; }
    }
    class A
    {
        public string name { get; set; }
        public string code { get; set; }
        public string type { get; set; }
    }
}

如果您想使用原始JSON数据格式,请更改DataContainer类的定义,使用Dictionary<string, Data>而不是List<Data>:

public class DataContainer
{
    public Dictionary<string, Data> Data { get; set; }
}

相关内容

  • 没有找到相关文章

最新更新