简体   繁体   中英

delete json element in a array of json c#

I have an array of json from the server. Like

ArrayExp = [
  {
    "id" : "number",
    "name" : "a name",
    ...
  }, 
  {
    "id" : "number",
    "name" : "a name",
    ...
  },
...
];

And I want to remove a "id" from all of the Array. I am trying with:

for (int i = 0; i < ArrayExp.Length; i++) {
    ArrayExp[i].id // I don't know how to remove it!
}

Can anyone help me?

ArrayExp elements are objects of anonymous type .

In order to remove property on it, you should map each element into new one without id .

var newArrayExpr = 
          ArrayExp
              .Select(it => new { it.name, ... });

I used ExpandoObject from System.Dynamic, hope it helps you

public static void Main()
{
    var arrayExp = GetArray();
    var newCollection = ArrayExp.ToList().Select(x => RedefineObject(x, "Id"));
}

static object[] GetArray()
{
    var person1 = new { Name = "name", Id = 1 };
    var person2 = new { Name = "name", Id = 2 };
    var person3 = new { Name = "name", Id = 3 };
    return new[] { person1, person2, person3 };
}

static object RedefineObject(object obj, string propertyToRemove)
{
    var properties = obj.GetType().GetProperties().Where(x => x.Name != propertyToRemove);

    var dict = new Dictionary<string, object>();
    var eobj = new ExpandoObject();
    var eoColl = (ICollection<KeyValuePair<string, object>>)eobj;

    properties.ToList().ForEach(x => dict.Add(x.Name, x.GetValue(obj)));

    dynamic dynObj = dict;
    return dynObj;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM