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"
}
]
CodePudding user response:
You might need to create some class to carry your JSON data, then use Newtonsoft.Json
library let your JSON data be objects
public class CustRecord
{
public string ID { get; set; }
public string Currency { get; set; }
public string CustomerNumber { get; set; }
public string CustomerName { get; set; }
}
public class Root
{
public List<CustRecord> CustRecord { get; set; }
}
Then use JsonConvert.SerializeObjec
method let your root.CustRecord
be an array JSON
var root = Newtonsoft.Json.JsonConvert.DeserializeObject<Root>(json);
var result = Newtonsoft.Json.JsonConvert.SerializeObject(root.CustRecord);
CodePudding user response:
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
});
CodePudding user response:
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; }
}