Home > Software engineering >  Remove an element from a JSON file in a test method
Remove an element from a JSON file in a test method

Time:08-15

I have a JSON File, as below, and I would like to remove a line/element of this, specifically the "FinanceDetails[LoanAmount]". How do I write this in C#.

"IntegratorID": "e20a5569-8e63-42ca-9f33-872d826276d0",
  "CorrelationID": "00000000-0000-0000-0000-000000000000",
  "ProposalID": 0,
  "Stage": "DECISION",
  "Request": "SendProposal",
  "PropertyValues": {
    "ExternalReference": "Integrator Reference",
    "ProposalType": "Private Individual",
    "Dealer[DealerID]": "9344",
    "FinanceDetails[Type]": "PCP",
    "FinanceDetails[CashDeposit]": "111",
    "FinanceDetails[Settlement]": "11",
    "FinanceDetails[PartExchange]": "22",
    "FinanceDetails[Term]": "72",
    "FinanceDetails[APR]": "12.9",
    "FinanceDetails[LoanAmount]": "0",
    "FinanceDetails[AnnualMileage]": "40000"
}

This is what I currently have, but not working.

public static void RemoveLineRequest(string fieldName)
{
    string sendProposalRequestSuccess = File.ReadAllText(sendProposalJSONFile);
    dynamic jsonObj = JsonConvert.DeserializeObject(sendProposalRequestSuccess);
    string output = jsonObj["PropertyValues"][fieldName];
    string finaloutput = JsonConvert.SerializeObject(output, Formatting.Indented);
    File.WriteAllText(sendProposalJSONFile, finaloutput);
}

CodePudding user response:

Do not deserialize to dynamic, use JObject (see the
Modifying JSON
doc):

var jsonObject = JsonConvert.DeserializeObject<JObject>(sendProposalRequestSuccess);
var propValues = (JObject)jsonObject["PropertyValues"];
propValues.Remove("FinanceDetails[LoanAmount]");

CodePudding user response:

Try jObjProperty.Remove()

public static void RemoveLineRequest(string fieldName, string sendProposalJSONFile)
{
    string sendProposalRequestSuccess = File.ReadAllText(sendProposalJSONFile);
    var jObj = JObject.Parse(sendProposalRequestSuccess);
    var jObjProperty = (JObject)jObj.SelectToken("PropertyValues");
    jObjProperty.Property(fieldName).Remove();
    File.WriteAllText(sendProposalJSONFile, jObj.ToString());
}
  • Related