c# - IEnumerable C# 对象到具有名称的数组的 JSON 对象

标签 c# json ienumerable

 public IEnumerable<Product> GetAllProdcut()
 {
     var products= _productRepository.GetAllProduct();
     return products;
 }

以上代码返回以下 JSON 对象:

[  
    {  
      "$id":"1",
      "Id":1,      
      "Name":"Dave",
      "Department":"IT",
    },
    {  
       "$id":"2",
      "Id":2,      
      "Name":"Dave",
      "Department":"IT",
    },
    {  
      "$id":"3",
      "Id":3,      
      "Name":"Dave",
      "Department":"IT",
    },
    {  
       "$id":"4",
      "Id":4,      
      "Name":"Dave",
      "Department":"IT",
    }
]

我需要的是在开头添加{ "data":,在结尾添加}

在开头添加 { "data": 并在结尾添加 } 的最佳方法是什么?

我不想使用字符串连接。

谢谢。

最佳答案

你只需要返回一个匿名对象:

public object GetAllProduct()
{
    var products= _productRepository.GetAllProduct();
    return new { data = products };
}

这是一个 fiddle 演示 - https://dotnetfiddle.net/nKRsnQ

关于c# - IEnumerable C# 对象到具有名称的数组的 JSON 对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25064468/

相关文章:

c# - 如何使 IsolatedStorageSettings 在设备/模拟器关闭后仍然存在?

c# - 更改成员资格、角色等的默认连接字符串

android - Android Studio 中 xml 上的图像在高度方向上异常拉伸(stretch)

javascript - Bootstrap typeahead 使用 json 对象而不是字符串

c# - 如何从 IEnumerable 中选择所有偶数位置项?

.net - 当类没有实现 IEnumerable 时,GetEnumerator 方法是否应该仍然是幂等的

c# - 如何使用 EPPlus 将数据从 csv 导入 Excel?

c# - 绘制光标时出现通用 GDI+ 异常 ~3322 次

php - Android - Kotlin : Sending a non empty jsonObject but receiving an empty one

c# - C#如何更新列表类型变量