'Remove the property name from JSON Array in C#

I've a JSON object containing an array like this:

{
    "CustRecord": [
        {
            "ID": "40274",
            "Currency": "USD",
            "CustomerNumber": "123456",
            "CustomerName": "contoso"
        },
        {
            "ID": "40275",
            "Currency": "USD",
            "CustomerNumber": "123456",
            "CustomerName": "contoso"
        }
    ]
}

and I want to remove the property name "CustRecord" from JSON to create the following output using C#. How can I achieve this?

[
        {
            "ID": "40274",
            "Currency": "USD",
            "CustomerNumber": "123456",
            "CustomerName": "contoso"
        },
        {
            "ID": "40275",
            "Currency": "USD",
            "CustomerNumber": "123456",
            "CustomerName": "contoso"
        }
]


Solution 1:[1]

In .NET 6 you can use the new "System.Text.Json.Nodes" namespace. It introduced JsonObject and JsonNode. You can do the following:

JsonNode original = JsonObject.Parse(jsonString);
string newJson = original["CustRecord"].ToJsonString();

If you want the serialized result to be indented (pretty) Json, then you can pass JsonSerializerOptions to ToJsonString():

string newJson = original["CustRecord"].ToJsonString(new JsonSerializerOptions 
{ 
     WriteIndented = true 
});

Solution 2:[2]

try this

var newJson=JObject.Parse(json)["CustRecord"].ToString();

or the most efficient way

json=json.Substring(0,json.Length-1).Substring(json.IndexOf(":")+1);

result

[
  {
    "ID": "40274",
    "Currency": "USD",
    "CustomerNumber": "123456",
    "CustomerName": "contoso"
  },
  {
    "ID": "40275",
    "Currency": "USD",
    "CustomerNumber": "123456",
    "CustomerName": "contoso"
  }
]

but if you need to deserialize json, not just parse , the best way would be

var customerRecord =JObject.Parse(json)["CustRecord"].ToObject<CustomerRecord>();

class

public class CustomerRecord
{
    public string ID { get; set; }
    public string Currency { get; set; }
    public string CustomerNumber { get; set; }
    public string CustomerName { get; set; }
}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 haldo
Solution 2