0

I have the following JSON object where I would like to search for the string: "Customer.CustomerAddress.Common" and replace it with "Customer.CustomerAddress.Common.S2" wherever it is present i.e. at all occurrences. How can this be done?

 {
   "$id": "1",
   "$type": "Customer.CustomerAddress, Customer.CustomerAddress.Common, Version=8.0.0.0, Culture=neutral, PublicKeyToken=f291d57f641e84e4",
   "FlatRate": 29.65,
   "AmountFinanced": 12402.2,
   "AmountUsed": 12302.2,
   "TotalPayment": 0,
   "CustomerAddress": {
      "$id": "2",
      "$type": "System.Collections.Generic.Dictionary`2[[System.String, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089],[System.Collections.Generic.List`1[[Customer.Customerbject, Customer.CustomerAddress.Common, Version=8.0.0.0, Culture=neutral, PublicKeyToken=f291d57f641e84e4]], mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]], mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089",
      "Items": {
         "$id": "3",
         "$type": "System.Collections.Generic.List`1[[Customer.Customerbject, Customer.CustomerAddress.Common, Version=8.0.0.0, Culture=neutral, PublicKeyToken=f291d57f641e84e4]], mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089",
         "$values": []
      },
      "Added": {
         "$id": "4",
         "$type": "System.Collections.Generic.List`1[[Customer.Customerbject, Customer.CustomerAddress.Common, Version=8.0.0.0, Culture=neutral, PublicKeyToken=f291d57f641e84e4]], mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089",
         "$values": []
      },
      "Removed": {
         "$id": "5",
         "$type": "System.Collections.Generic.List`1[[Customer.Customerbject, Customer.CustomerAddress.Common, Version=8.0.0.0, Culture=neutral, PublicKeyToken=f291d57f641e84e4]], mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089",
         "$values": []
      }
   }
   }
1

1 Answer 1

1

We go through all the descendants, find properties with the desired name and value, then replace the value with the desired one.

var text = File.ReadAllText("test.json");
var json = JObject.Parse(text);

var props = json.Descendants()
    .OfType<JProperty>()
    .Where(p => p.Name == "$type" &&
        p.Value.ToString().Contains("Customer.CustomerAddress.Common"));

foreach (var p in props)
{
    p.Value = p.Value.Value<string>()
        .Replace("Customer.CustomerAddress.Common", "Customer.CustomerAddress.Common.S2");
}

File.WriteAllText("result.json", json.ToString());
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.