Below is the code
json - just want JsonLookupData in the response
{
"LookupType": "ABC",
"BusSegmentName": "Test",
"PolcyObjectId": "999",
"JsonLookupData": {
"data": {
"OBJ_ID": "9393",
"ABC": "JAJA",
"XYZ": "LL",
"AAA": "250.00"
}
}
}
public new dynamic input { get; set; }
//initialization
input = JsonConvert.DeserializeObject(jsonInput.ToString());
//trying to remove all attributes except JsonLookupData
input.Properties().Where
(x => !x.Name.Equals("JsonLookupData")).ToList().ForEach(x => x.Remove());
Is there any way to delete the properties directly from the dynamic input (Don't want to assign it to JObject first).
above code is giving the below error
Cannot use a lambda expression as an argument to a dynamically dispatched operation without first casting it to a delegate or expression tree type
While a JObject is still the right choice, you can still use dynamic as long as you do not use lambda expressions that are reliant on dynamic dispatch.
By assigning the output of input.Properties() to a non-dynamic type (IEnumerable<dynamic>), we can perform operations in a lambda expression.
input = JsonConvert.DeserializeObject(jsonInput.ToString());
IEnumerable<dynamic> props = input.Properties();
props.Where(x => !x.Name.Equals("JsonLookupData")).ToList().ForEach(x => x.Remove());
string xx = JsonConvert.SerializeObject(input);
This outputs:
{"JsonLookupData":{"data":{"OBJ_ID":"9393","ABC":"JAJA","XYZ":"LL","AAA":"250.00"}}}
Alternatively, you can avoid Linq altogether.
input = JsonConvert.DeserializeObject(jsonInput);
// create a separate tracking collection so that we
// do not modify the collection we are iterating
var propsToRemove = new List<JProperty>();
foreach (var prop in input.Properties())
{
if (!prop.Name.Equals("JsonLookupData"))
{
propsToRemove.Add(prop);
}
}
propsToRemove.ForEach(x => x.Remove());
string xx = JsonConvert.SerializeObject(input);
This outputs:
{"JsonLookupData":{"data":{"OBJ_ID":"9393","ABC":"JAJA","XYZ":"LL","AAA":"250.00"}}}
for your sample JSON.