使用JSON.NET从datatable创建JSON

时间:2016-02-23 05:24:53

标签: .net json json.net automapper

我从数据库查询中获取数据表,我需要从中创建一个JSON。 如果我使用JSON.NET直接序列化数据表,我会得到以下内容,

[{"Item_CODE":"A08","ITEM_NAME":"sampleName","ITEM_LOCATION":"Kolkata"}]

但是我正在寻找以下JSON格式,

{
 "Codes": ["A08","A09","A10"],
 "ITEM_NAME": "sampleName",
 "ITEM_LOCATION": "Kolkata",
 }

我知道没有直接的方法可以做到这一点。那么我需要循环遍历数据表并动态创建JSON吗? 我正在查看Automapper库,并且有兴趣了解它是否可以这样做。 如何映射自动播放器的JSON?

1 个答案:

答案 0 :(得分:1)

一种可能的解决方案是使用自定义转换器并控制序列化 -

var settings = new JsonSerializerSettings();
settings.Converters.Add(new CustomConverter());
var json = JsonConvert.SerializeObject(o, settings);
// {"Codes":["A08","A09","A10"],"ITEM_NAME":"sampleName","ITEM_LOCATION":"Kolkata"}

internal class Product
{
    public List<string> Item_CODE { get; set; }
    public string ITEM_NAME { get; set; }
    public string ITEM_LOCATION { get; set; }
}

internal class CustomConverter : JsonConverter
{
    public override bool CanConvert(Type objectType)
    {
        return true;
    }

    public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
    {
        throw new NotImplementedException();
    }

    public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
    {
        var data = value as DataTable;
        if (data != null)
        {
            var res = new Product
            {
                Item_CODE = new List<string>()
            };
            foreach (DataRow row in data.Rows)
            {
                res.Item_CODE.Add((string)row[0]);
                if (string.IsNullOrWhiteSpace(res.ITEM_NAME)) res.ITEM_NAME = (string)row[1]; ;
                if (string.IsNullOrWhiteSpace(res.ITEM_LOCATION)) res.ITEM_LOCATION = (string)row[2];
            }

            writer.WriteStartObject();
            writer.WritePropertyName("Codes");
            writer.WriteStartArray();
            res.Item_CODE.ForEach(a => writer.WriteValue(a));
            writer.WriteEndArray();
            writer.WritePropertyName("ITEM_NAME");
            writer.WriteValue(res.ITEM_NAME);
            writer.WritePropertyName("ITEM_LOCATION");
            writer.WriteValue(res.ITEM_LOCATION);
            writer.WriteEnd();
        }
    }
}