【问题标题】:Modify the structure of a json修改一个json的结构
【发布时间】:2018-12-04 15:46:50
【问题描述】:

我正在尝试修改 json 中的以下文本。以下链结构如下:

  {
  "cabecera": {
    "tipo_cambio": "",
    "fecha_emision": "",
    "total": ""
  },
  "detalle": {
    "940b130369614bd6b687dc5b41623439": {
      "producto": "94115891",
      "detalle_adicional": "",
      "cantidad": "",
      "precio_unitario": "",
      "subtotal": "",
      "total": ""
    },
    "6cbdcef2bbff4b059c8de7432c9aa5f2": {
      "producto": "6738756",
      "detalle_adicional": "",
      "cantidad": "",
      "precio_unitario": "",
      "subtotal": "",
      "total": ""
    }
  }
}

我想将其修改为以下结构,以便“940b130369614bd6b687dc5b41623439”之类的代码消失,dtalle 变为数组。

{
  "cabecera": {
    "tipo_cambio": "",
    "fecha_emision": "",
    "total": ""
  },
  "detalle": [
    {
      "producto": "94115891",
      "detalle_adicional": "",
      "cantidad": "",
      "precio_unitario": "",
      "subtotal": "",
      "total": ""
    },
    {
      "producto": "6738756",
      "detalle_adicional": "",
      "cantidad": "",
      "precio_unitario": "",
      "subtotal": "",
      "total": ""
    }
  ]
}

有没有办法在 C# 中做到这一点?

【问题讨论】:

  • 您自己尝试过吗?你知道你想用哪种语言来做吗?
  • 用动态类型试试,.Net中的JArray.Parse

标签: javascript c# json


【解决方案1】:

这是一个解决问题的小C#程序

string origJson =
@"{
""cabecera"": {
    ""tipo_cambio"": """",
    ""fecha_emision"": """",
    ""total"": """"
},
""detalle"": {
    ""940b130369614bd6b687dc5b41623439"": {
    ""producto"": ""94115891"",
    ""detalle_adicional"": """",
    ""cantidad"": """",
    ""precio_unitario"": """",
    ""subtotal"": """",
    ""total"": """"
    },
    ""6cbdcef2bbff4b059c8de7432c9aa5f2"": {
        ""producto"": ""6738756"",
        ""detalle_adicional"": """",
        ""cantidad"": """",
        ""precio_unitario"": """",
        ""subtotal"": """",
        ""total"": """"
    }
}
}";

JObject obj = JObject.Parse(origJson);
JArray detalleChilds = new JArray(obj.SelectToken("detalle").Select(x => x.Children()));

obj.Remove("detalle");
obj.Add("detalle", detalleChilds);

Console.WriteLine(obj);

为了使用这个例子,你需要安装 Newtonsoft.Json NuGet

<PackageReference Include="Newtonsoft.Json" Version="11.0.2" />

【讨论】:

  • 非常感谢
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-11-28
  • 1970-01-01
  • 2020-06-13
  • 1970-01-01
  • 2020-05-23
相关资源
最近更新 更多