Remove children property based on Parent property from Json object using C#.net

json string have parent and child and child has sub child(grand child). Here wanted to remove grand child. child name and grand child name is same so if i remove based on the name it will remove child and grand child.But I wanted to remove only GrandChild property. I have converted json string to JObject here my code snippet: i know this is wrong it deletes both child and grand child because names are same. Please find attached my Json object structure and json string. I am using C#.net. Please let me know if you need any information.

JObject jObject = JObject.Parse(jsonString);
jObject.Descendants()
.OfType<jproperty>()
.Where(attr => attr.Name.Contains("NameofChild"))
.ToList()
.ForEach(attr => attr.Remove());
json-string.txt
jsonStructure.jpg
victor sAsked:
Who is Participating?

[Product update] Infrastructure Analysis Tool is now available with Business Accounts.Learn More

x
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

it_saigeDeveloperCommented:
No attached JSON.

-saige-
0
victor sAuthor Commented:
attached json string.
0
it_saigeDeveloperCommented:
Ok I think I understand what you are looking for, but, to clarify, can you give me a couple of example children/grandchildren that you want to remove.  Just browsing through the data, I did not find any childlren/grandchildren pairs which matched explicitly by name.

-saige-
0
CompTIA Security+

Learn the essential functions of CompTIA Security+, which establishes the core knowledge required of any cybersecurity role and leads professionals into intermediate-level cybersecurity jobs.

Kelvin McDanielSr. DeveloperCommented:
IMHO you're going about this the wrong way. For the scenario you've painted, the most performant way of doing this is to use the strongly-typed classes and arguments to arrive at your desired result.

First, I get a strongly-typed hierarchy by using Visual Studio's "Edit >> Past Special >> Paste JSON As Classes" feature. You can get the same result by using a tool such as http://json2csharp.com/. Then, I add those classes to the code handling the processing. I'm betting that this code could be optimized further -- for instance, to get rid of the loops -- but I can't spend any more time on this today.  :)

Working .NETFiddle: https://dotnetfiddle.net/Widget/EZlosN

OUTPUT:
BASIS: ProductRules.Children: Any with Children? True
UPDATE: ProductRules.Children: Any with Children? False

using System;
using System.Linq;
using System.Net.Http;
using Newtonsoft.Json;
					
public class Program
{
	public static void Main()
	{
		var client = new HttpClient();
		var json = client.GetStringAsync("https://filedb.experts-exchange.com/incoming/2018/09_w39/1388389/json-string.txt").Result;
		var productList = JsonConvert.DeserializeObject<ProductList>(json);
		//Console.WriteLine(productList);

		var thereAreGrandChildrenCheck0 = productList.ProductRules.Any(x => x.RulesProduct.ChildProducts.Any(child => child.ChildProducts.Any(grandChild => grandChild != null && grandChild.ChildProducts != null)));
		Console.WriteLine(string.Format("BASIS: ProductRules.Children: Any with Children? {0}", thereAreGrandChildrenCheck0));

		foreach (var rule in productList.ProductRules)
		{
			foreach (var product in rule.RulesProduct.ChildProducts)
			{
				foreach (var child in product.ChildProducts)
				{
					child.ChildProducts = null;
				}
			}
		}

		//Console.WriteLine(productList);
		var thereAreGrandChildrenCheck1 = productList.ProductRules.Any(x => x.RulesProduct.ChildProducts.Any(child => child.ChildProducts.Any(grandChild => grandChild != null && grandChild.ChildProducts != null)));
		Console.WriteLine(string.Format("UPDATE: ProductRules.Children: Any with Children? {0}", thereAreGrandChildrenCheck1));
	}
	
	public class ProductList
	{
		public Address Address { get; set; }
		public string SalesChannel { get; set; }
		public Productrule[] ProductRules { get; set; }
		public object Customer { get; set; }
		public object ContractDate { get; set; }
		public object Agent { get; set; }
		public object IdentityOrg { get; set; }
		public object AsOfDate { get; set; }
	}

	public class Address
	{
		public int AddressType { get; set; }
		public string ID { get; set; }
		public string Address1 { get; set; }
		public object Address2 { get; set; }
		public string City { get; set; }
		public string State { get; set; }
		public string PostalCode { get; set; }
		public string Country { get; set; }
		public object FullAddress { get; set; }
		public Propertyinformation PropertyInformation { get; set; }
		public object ValidationError { get; set; }
		public object Metadata { get; set; }
	}

	public class Propertyinformation
	{
		public string DwellingType { get; set; }
		public object DateBuilt { get; set; }
		public object Size { get; set; }
	}

	public class Productrule
	{
		public Rulesproduct RulesProduct { get; set; }
	}

	public class Rulesproduct
	{
		public Childproduct[] ChildProducts { get; set; }
		public string ProductID { get; set; }
		public string ProductVersionID { get; set; }
		public string Name { get; set; }
		public string Description { get; set; }
		public DateTime EffectiveDate { get; set; }
		public bool Enabled { get; set; }
		public bool IsSellable { get; set; }
		public bool IsOptional { get; set; }
		public string SalesChannel { get; set; }
		public object ServiceFee { get; set; }
		public object Quantity { get; set; }
	}

	public class Childproduct
	{
		public Childproduct[] ChildProducts { get; set; }
		public string ProductID { get; set; }
		public string ProductVersionID { get; set; }
		public string Name { get; set; }
		public string Description { get; set; }
		public DateTime EffectiveDate { get; set; }
		public bool Enabled { get; set; }
		public bool IsSellable { get; set; }
		public bool? IsOptional { get; set; }
		public object SalesChannel { get; set; }
		public object ServiceFee { get; set; }
		public object Quantity { get; set; }
	}
}

Open in new window

0

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
Chinmay PatelChief Technical NinjaCommented:
Bit of a hack, If this ChildProducts are always going to be a null value

How about removing it from the string itself? i.e.

jsonText.Replace("ChildProducts\": [],", string.Empty);
            JObject jObject = JObject.Parse(jsonText);

Open in new window


Otherwise, you can check if the ChildProducts has any children, if so do not remove it.
0
it_saigeDeveloperCommented:
Looking at the data, I believe that the user only wants to remove certain grandchildren, not all, but I wanted clarification on this point.

-saige-
1
victor sAuthor Commented:
solution given by Kelvin McDaniel is working perfectly for my requirements. I just modified a little bit removed inner foreach loop to get my desired result. appreciate your help.
1
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
.NET Programming

From novice to tech pro — start learning today.