【问题标题】:How to remove column name in JSON return C#如何在 JSON 返回 C# 中删除列名
【发布时间】:2020-01-24 01:43:51
【问题描述】:

我在下面有一个 JSON 输出:

[
    {
        positionCode: "POS1",
        positionName: "POSITION 1",
        positionDescription: "",
        parentPosition: "POS2",
    },
    {
        positionCode: "POS2",
        positionName: "POSITION 2",
        positionDescription: "",
        parentPosition: "POS3",
    }
]

此 JSON 结果来自我的 Web API,如下所示:

    return new JsonResult(query.Select(x => 
    new { x.PositionCode, x.PositionName , x.PositionDescription , x.ParentPosition }).ToList());

但是,我想要的输出是这样的:

应该做些什么来达到我想要的结果?在我的 javascript 代码中还是在我的 C# Web API 中?谢谢!

【问题讨论】:

  • 你试过new string[] { x.PositionCode, x.PositionName , x.PositionDescription , x.ParentPosition }吗?
  • @mjwills 成功了!非常感谢!能否请您发布此内容,以便我可以将您的答案标记为已选中。谢谢。

标签: javascript c# arrays json api


【解决方案1】:

假设您有类似的设置:

var data = new List<PositionClass>
{
    new PositionClass { PositionCode = "POS1", PositionName = "POSITION 1", PositionDescription = "", ParentPosition = "POS2" },
    new PositionClass {  PositionCode = "POS2", PositionName = "POSITION 2", PositionDescription = "", ParentPosition = "POS2" }
};

你有两个选择:

在您的 C# 代码中处理它

看起来您已经拥有linq,所以只需将您的List&lt;T&gt; 转换为数组或字符串:

data.Select(d => new[] {d.ParentPosition, d.PositionCode, d.PositionDescription, d.PositionName}).ToArray()

在您的 JavaScript 代码中处理它

const response = [{
    positionCode: "POS1",
    positionName: "POSITION 1",
    positionDescription: "",
    parentPosition: "POS2",
  },
  {
    positionCode: "POS2",
    positionName: "POSITION 2",
    positionDescription: "",
    parentPosition: "POS3",
  }
];

const reformatted = response.map(r => Object.values(r))

console.log(reformatted);

【讨论】:

    【解决方案2】:

    JavaScript 的 Object.values() 可用于执行此操作。

    var data = [{ positionCode: "POS1", positionName: "POSITION 1", positionDescription: "", parentPosition: "POS2", }, { positionCode: "POS2", positionName: "POSITION 2", positionDescription: "", parentPosition: "POS3", }]; 
    
    var result = [];
    
    data.forEach(item => {
      result.push(Object.values(item));
    });
    
    console.log(result);

    【讨论】:

      【解决方案3】:

      当你想要一个字符串值的数组时,你正在选择一个具有字符串属性的匿名对象。

      return new JsonResult(query.Select(x => 
          new string[] { 
             x.PositionCode, 
             x.PositionName, 
             x.PositionDescription, 
             x.ParentPosition 
          }).ToList()
      );
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2021-08-07
        • 2021-12-31
        • 1970-01-01
        • 1970-01-01
        • 2011-02-26
        • 1970-01-01
        • 2015-01-23
        • 1970-01-01
        相关资源
        最近更新 更多