在c#中动态将Json输出结果转换为Json数组格式

问题描述 投票:0回答:1

在 Windows 应用程序中,我得到的 Json 输出如下:

"Detail": {
    "ServiceStartDate": "7/28/2021 12:00:00 AM",
    "ServiceEndDate": "7/28/2021 12:00:00 AM",
    "PlaceOfService": "Mumbai",
    "ServiceName": "Claim",
    "Procedure": "Insurance",
    "Modifier": "B",
    "DiagCodePointer": "xyz",
    "Count": "2",
    "Cost": "33.3",
    "ChargeAmount": "66.6"
  }

但我希望它是这样的:

"Detail": [
    {
      "ServiceStartDate": "7/28/2021 12:00:00 AM",
      "ServiceEndDate": "7/28/2021 12:00:00 AM",
      "PlaceOfService": "Mumbai",
      "ServiceName": "Claim",
      "Procedure": "Insurance",
      "Modifier": "B",
      "DiagCodePointer": "xyz",
      "Count": "2",
      "Cost": "33.3",
      "ChargeAmount": "66.6"
    }
  ]

只要有单个记录,结果就不会以数组格式出现。 我希望它是动态的,而不需要对元素名称进行硬编码......

我正在使用

Newtonsoft.Json

创建这样的 json 对象

JObject DtlJsn = JObject.Parse(DtlXml);

仅当有单个记录时,它才不会以数组形式出现,否则没有问题。

请帮我解决这个问题

c# json.net desktop
1个回答
0
投票

要使用 Newtonsoft.Json 将 JSON 输出动态转换为 C# 中的数组格式,您可以检查“详细信息”部分中的记录数并相应地处理转换。

这是一个例子:

using Newtonsoft.Json;
using Newtonsoft.Json.Linq;

// Assuming DtlXml contains your JSON string

// Parse the JSON string
JObject DtlJsn = JObject.Parse(DtlXml);

// Check if the "Detail" section contains a single record or an array of records
JToken detailToken = DtlJsn["Detail"];

if (detailToken != null)
{
    if (detailToken is JObject)
    {
        // If there's a single record, convert it to an array of one object
        JArray detailArray = new JArray();
        detailArray.Add(detailToken);
        DtlJsn["Detail"] = detailArray;
    }
    // If it's already an array or multiple records, it remains unchanged
}

// Convert the modified JObject back to JSON string
string modifiedJson = DtlJsn.ToString(Formatting.None); // You can choose formatting options as needed

// Now `modifiedJson` contains the JSON with "Detail" represented as an array, even for a single record

此代码检查“详细信息”部分是否包含单个记录或多个记录。如果它是一条记录,它会将其转换为内部有一个对象的数组格式。如果它已经是一个数组或多条记录,则保持不变。

这样,您可以确保“详细信息”部分表示为数组,满足动态要求,而无需硬编码元素名称。

© www.soinside.com 2019 - 2024. All rights reserved.