简体   繁体   English

使用C#将JSON字符串反序列化为DataTable / DataSet

[英]Deserialize JSON String into DataTable / DataSet using c#

I have following JSON String 我有以下JSON字符串

{
"1":[
        {"cityId":93,"cityName":"Tapah","cityCode":"TAP"},
        {"cityId":3,"cityName":"Melaka","cityCode":"MLK"},
        {"cityId":6,"cityName":"Kota Bharu","cityCode":"KB"},
        {"cityId":7,"cityName":"Dungun","cityCode":"DG"}
    ],
"2":[
        {"cityId":77,"cityName":"Grik","cityCode":"GRIK"},
        {"cityId":6,"cityName":"Kota Bharu","cityCode":"KB"},
        {"cityId":7,"cityName":"Dungun","cityCode":"DG"},
        {"cityId":98,"cityName":"Bangan Serai","cityCode":"BS"}
    ],
"6":[
        {"cityId":3,"cityName":"Melaka","cityCode":"MLK"},
        {"cityId":82,"cityName":"Teluk Intan","cityCode":"TI"},
        {"cityId":7,"cityName":"Dungun","cityCode":"DG"}
    ]
}

When I using JSON.NET 当我使用JSON.NET时

DataSet obj = JsonConvert.DeserializeObject(responseBody); 数据集obj = JsonConvert.DeserializeObject(responseBody);

I am getting following Table only 我只跟随表

cityId  |  cityName   | cityCode
-----------------------------------
93           Tapah          TAP
3            Melaka         MLK
6            Kota Bharu     KB
7            Dungun         DG

I need to like this 我需要这样

from  |    cityId  |  cityName   | cityCode
-----------------------------------------------
 1            93           Tapah          TAP
 1            3            Melaka         MLK
 1            6            Kota Bharu     KB
 1            7            Dungun         DG
 2            77           Grik           GRIK
 2            6            Kota Bharu     KB
 2            7            Dungun         DG
 2            98           Bangan Serai   BS
 6            3            Melaka         MLK
 6            82           Teluk Intan    TI
 6            7            Dungun         DG             

The reason for the issue is the incorrect usage of the JsonConvert.DeserializeObject following should work in this case: 该问题的原因是在这种情况下, JsonConvert.DeserializeObject用法不正确:

Define a type / schema with the columns details (as shown in above response) 使用列详细信息定义类型/架构(如上面的响应所示)

public class City
{
    public int cityId;
    public string cityName;
    public string cityCode;
}

Now what you are getting in response body is the type, Json is by default key value pair 现在,您在响应正文中得到的是类型,默认情况下,Json是键值对

Dictionary<object, List<City>>

Now your deserialization code should be: 现在,您的反序列化代码应为:

var obj = JsonConvert.DeserializeObject<Dictionary<object, List<City>>>(responseBody);

obj will be of the type Dictionary<object, List<City>> obj的类型为Dictionary<object, List<City>>

Now create the Schema of the Custom Dataset object as follows: 现在,如下创建“自定义数据集”对象的架构:

public class CustomDataset
    {
        public object from;
        public int cityId;
        public string cityName;
        public string cityCode;
    }

Use simple foreach to create the custom dataset from obj type as follows: 使用简单的foreach从obj类型创建自定义数据集,如下所示:

List<CustomDataset> cdList = new List<CustomDataset> ();

foreach(object key in obj.Keys)
{
foreach(City c in obj[key])
{
  cdList.Add(key, c.cityId, c.cityName, cityCode);
}
}

cdList of type List<CustomDataset> wil be your return containing solution you need. 类型为List<CustomDataset> cdList将是包含所需解决方案的退货。 Final part using Foreach can be skipped if you use Linq, which would be simple as follows: 如果您使用Linq,则可以跳过使用Foreach的最后一部分,这很简单,如下所示:

List<CustomDataset> cdList = 
                              obj.SelectMany(x => x.Value.Select(y =>
                                               new CustomDataset
                                               {
                                                from = x.Key,
                                                cityId = y.cityId,
                                                cityName = y.cityName,
                                                cityCode =  y.cityCode
                                               }
                                               )).ToList();

I suggest de-serializing JSON objects to framework types that are semantically equivalent. 我建议将JSON对象反序列化为在语义上等效的框架类型。 In your case, the JSON is semantically equivalent to IDictionary<TKey, ICollection<TValue>>> 在您的情况下,JSON在语义上等效于IDictionary<TKey, ICollection<TValue>>>

IDictionary<int, ICollection<City>> cities;
cities = JsonConvert.DeserializeObject<IDictionary<int, ICollection<City>>>(responseBody);

Then, do the DataSet conversion yourself instead of relying on reflection. 然后,执行DataSet转换自己而不是依靠反射。

var dataSet = new DataSet();
var dataTable = dataSet.Tables.Add();
dataTable.Columns.Add("from");
dataTable.Columns.Add("cityId");
dataTable.Columns.Add("cityName");
dataTable.Columns.Add("cityCode");

// foreach KeyValuePair in IDictionary<TKey, ICollection<TValue>>
foreach (var cityGroup in cities)
{
    // foreach TValue in ICollection<TValue>
    foreach (var city in cityGroup.Value)
    {
        dataTable.LoadDataRow(
            new object[]
            {
                cityGroup.Key,
                city.cityId,
                city.cityName,
                city.cityCode
            },
            LoadOption.PreserveChanges);
    }
}

For TValue , I used a simple data contract class. 对于TValue ,我使用了一个简单的数据协定类。

public class City
{
    public int cityId;
    public string cityName;
    public string cityCode;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM