简体   繁体   中英

Add JObject to JArray on nth position

I'm currently working on an ASP.NET Web API .NET Framework 4.7.2. I try to alter some JSON data in my service class. I try to add a new object after every 2nd object in my JArray.

I thought about manipulating the JSON data, rather then concrete objects because the received data will most likely be dynamic data. I'm using the library JObject, but I'm getting some error without any real exception messages.

My received JSON structure looks like that:

{ "data" : [
   {"IsPlaceholder": 0, "Name" : "Test1", "Size" : 2 },
   {"IsPlaceholder": 0, "Name" : "Test2", "Size" : 3 },
   {"IsPlaceholder": 0, "Name" : "Test3", "Size" : 1 }
]}

My service class looks like that:

public class MyService : IMyService
{
    public async Task<JObject> UpdateInformationAsync(JObject coolData)
    {    
        // Random placeholder, new placeholder object after 2nd
        var placeholder = JObject.FromObject(new PlaceholderVm());
        var cnt = 0;

        foreach (JObject c in coolData["data"] as JArray)
        {
            if (cnt % 2 == 0)
            {
                coolData["data"][cnt].AddAfterSelf(placeholder);
            }
            cnt++;
        }

        return coolData;
    }
}

My placeholder view model looks like that:

public class PlaceholderVm
{
    public int IsPlaceholder => 1;
    public string Name => "Placeholder";
    public float Size { get; set; } = 0;
}

When I try to add a placeholderVm to my JArray, it works fine the first time, but on the 2nd iteration it throws an error without exception message.

Do you know how I can add a new JObject on nth position to my JArray?

Thank you!

This is because you are mutating the underlying collection while looping through it in the foreach . This is the reason you'll often times see folks initialize a new List<T> when doing operations like this, to avoid this error.

It actually yields this exception :

Run-time exception (line 21): Collection was modified; enumeration operation may not execute.

System.InvalidOperationException: Collection was modified; enumeration operation may not execute.

The easiest way around it is to simply create a new collection and place things where you want them to go. In your case, this may look like :

    var jObject = new JObject();
    JArray jArray = new JArray();

     foreach (JObject c in coolData["data"] as JArray)
    {
         jArray.Add(c);

        if (cnt % 2 == 0)
        {
            jArray[jArray.Count - 1].AddAfterSelf(placeholder);
        }
        cnt++;
    }

    jObject.Add("data", jArray);

Here's a .NET Fiddle

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