skip to Main Content

I have a json string that has nested values:

{
"card": {
"number": "411111111111111111",
"expirationMonth": null,
"expirationYear": null,
"securityCode": null
}
}

I want to remove expirationMonth, expirationYear, securityCode so that only card: number remain. but I can’t find any example of how to do this with system.text.json that aren’t wickedly complex and involve basically writing your own extension library.

Here is what I’ve tried:

            JsonObject requestJson = JsonSerializer.Deserialize<JsonObject>(jsonString);
            requestJson.Remove("expirationMonth");
            requestJson.Remove("expirationYear");
            requestJson.Remove("securityCode");

But since the elements are nested JsonObject.Remove does nothing.

2

Answers


  1. I wrote with 2 ways

    Use system.text.json

    JsonObject requestJson = JsonSerializer.Deserialize<JsonObject>(jsonString);
    
    var card = requestJson["card"].AsObject();
    
    card.Remove("expirationMonth");
    
    card.Remove("securityCode");
    card.Remove("expirationYear");
    
    

    use Newtonsoft.Json

    
    var objd = JObject.Parse(jsonString);
     objd.Value<JObject>("card").Remove("expirationMonth");
     objd.Value<JObject>("card").Remove("expirationYear");
     objd.Value<JObject>("card").Remove("securityCode");
    
    Console.WriteLine(objd);
    
    
    
    Login or Signup to reply.
  2. you forgot about a root property. should be

    ((JsonObject)requestJson["card"]).Remove("expirationMonth");
    //... and so on
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search