JSON.Net将集合序列化为数组数组

时间:2016-11-23 16:05:34

标签: c# arrays json datatables json.net

默认情况下,DataTables Ajax期望JSON数据是一个数组数组。

使用JsonConverter是否可以通过属性/设置将集合序列化为数组而不是对象数组,或者是否必须通过自定义public class DeviceIndex { public int Id { get; set; } [Display(Name = "Asset Tag")] public string AssetTag { get; set; } [Display(Name = "Lease End")] [DataType(DataType.Date)] public DateTime LeaseEndDate { get; set; } public string Type { get; set; } [Display(Name = "Operating System")] public string OperatingSystem { get; set; } public string Model { get; set; } } 来完成。我试图序列化的对象如下:

public IActionResult IndexJson()
{
    var model = _db.Devices.Select(d => new DeviceIndex { ... }).ToList();
    return Content(JsonConvert.SerializeObject(new { data = model }), "application/json");
}

我的控制器操作如下:

{
  "data": [
    {
      "Id": 1649,
      ...
    },
    {
      "Id": 703,
      ...
    }
  ]
}

输出JSON:

{
  "data": [
    [
      "1649",
      ...
    ],
    [
      "703",
      ...
    ]
  ]
}

虽然我想要的结果如下:

[JsonArray]
public class DevicesIndex: IEnumerable<DeviceIndex>
{
    List<DeviceIndex> devices;

    public IEnumerator<DeviceIndex> GetEnumerator()
    {
        return devices.GetEnumerator();
    }

    IEnumerator IEnumerable.GetEnumerator()
    {
        return GetEnumerator();
    }
}

我以为我可以为我的集合使用JsonArray属性,但它不会改变输出。

<xsd:simpleType name="PType">
  <xsd:restriction base="xsd:string">
    <xsd:enumeration value="P" />
    <xsd:enumeration value="P2" />
  </xsd:restriction>
</xsd:simpleType>

2 个答案:

答案 0 :(得分:2)

您可以通过简单的方式实现它,只需使用此简单示例更新您的IndexJson()方法。

您需要序列化List<List<object>>,请尝试此示例。这是List<string>的列表。

public IActionResult IndexJson()
    {
        List<List<string>> data = new List<List<string>>();

        data.Add(new List<string>(new string[] {"test1", "test2"}));
        data.Add(new List<string>(new string[] {"test3", "test4"}));

        var json = JsonConvert.SerializeObject(new {data = data});
        return Content(json, "application/json");
    }

你会得到这个JSON

{
  "data":[
    ["test1","test2"],
    ["test3","test4"]
]}

使用您的数据模型

   List<List<string>> data =new List<List<string>>();

        List<DeviceIndex> deviceIndex = new List<DeviceIndex>();
        DeviceIndex item = new DeviceIndex();
        item.Id = 111;
        item.AssetTag = "Tag";
        item.LeaseEndDate = DateTime.Now;
        item.Type = "Type";
        item.OperatingSystem = "OS";
        item.Model = "Model";

        deviceIndex.Add(item);
        deviceIndex.Add(item);

        foreach (var device in deviceIndex)
        {

            data.Add(new List<string>(new string[] { device.Id.ToString(), device.AssetTag, device.AssetTag, device.OperatingSystem }));
        }

       var json =  JsonConvert.SerializeObject(new {data= data });

JSON

{
 "data":[
   ["111","Tag","Tag","OS"],
   ["111","Tag","Tag","OS"]
  ]
}

答案 1 :(得分:0)

看起来自定义JsonConverter是建议的方法

public class DeviceIndexJsonConverter : JsonConverter
{
    public override bool CanConvert(Type objectType)
    {
        return objectType == typeof(DeviceIndex);
    }

    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)
    {
        if (value == null) return;

        writer.WriteStartArray();

        var properties = value.GetType().GetProperties();
        foreach (var property in properties)
            writer.WriteValue(value.GetType().GetProperty(property.Name).GetValue(value));

        writer.WriteEndArray();
    }
}