如何以编程方式从动态 JObject 中删除 属性

How to delete property from dynamic JObject programmatically

下面是代码

json - 只需要响应中的 JsonLookupData

{
  "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());
  

有没有办法直接从动态input中删除属性(不想先赋值给JObject)

上面的代码给出了下面的错误

Cannot use a lambda expression as an argument to a dynamically dispatched operation without first casting it to a delegate or expression tree type

虽然 JObject 仍然是正确的选择,但您仍然可以使用 dynamic 只要您不使用依赖于动态调度的 lambda 表达式。

通过将input.Properties()的输出分配给非动态类型(IEnumerable<dynamic>),我们可以在lambda表达式中执行操作。

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);

这输出:

{"JsonLookupData":{"data":{"OBJ_ID":"9393","ABC":"JAJA","XYZ":"LL","AAA":"250.00"}}}

或者,您可以完全避免使用 Linq。

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);

这输出:

{"JsonLookupData":{"data":{"OBJ_ID":"9393","ABC":"JAJA","XYZ":"LL","AAA":"250.00"}}}

你的样本 JSON。