0

I am using C# Newtonsoft to represent data I have in JSON.

I am trying to selectively create a new JObject from an existing JObject by specifying which properties / sub properties I want.

Example code below:

var jobject = JObject.Parse(jsonText);

var list = new List<JToken>()
{
   jobject["A"],
   jobject["B"]["C"],
   jobject["B"]["D"],
   jobject["B"]["E"]["F"]
}

Combine(list);

JObject Combine(List<JToken> list)
{
   /// What to put in here?
}

The expected output that I want, is Json that would be something like this, (Depending upon what the input jobject is)

{
  "A" : <Data of jobject["A"]>,
  
  "B" : 
  {
     "C" : <Data of jobject["B"]["C"]>,
       
       "D" : <Data of jobject["B"]["D"]>,
       
       "E" : 
       {
         "F" : <Data of jobject["B"]["E"]["F"]>
       }
  }
}

The source jobject may contain many other properties / fields. the final JToken created will be unique, but a given property used in a chain may not be (in this example, you can see jobject["B"] is used 3 times as first item)

Pavel Anikhouski
  • 21,776
  • 12
  • 51
  • 66
Ilan Keshet
  • 514
  • 5
  • 19
  • 1
    Your question lacks a [mcve], but perhaps `JsonExtensions.RemoveAllExcept(this TJToken obj, IEnumerable paths)` from [this answer](https://stackoverflow.com/a/30333562/3744182) to [How to perform partial object serialization providing “paths” using Newtonsoft JSON.NET](https://stackoverflow.com/q/30304128/3744182) might meet your needs. – dbc Oct 27 '20 at 07:06
  • Yes thanks! I used JObject.Remove to solve the problem! – Ilan Keshet Oct 27 '20 at 16:04
  • @dbc also, I don't understand what you mean by minimal reproducible example. It seems pretty clear to me... the jsonText could be any valid json. – Ilan Keshet Oct 27 '20 at 16:07

0 Answers0