简体   繁体   English

在第n个位置将JObject添加到JArray

[英]Add JObject to JArray on nth position

I'm currently working on an ASP.NET Web API .NET Framework 4.7.2. 我目前正在使用ASP.NET Web API .NET Framework 4.7.2。 I try to alter some JSON data in my service class. 我尝试在服务类中更改一些JSON数据。 I try to add a new object after every 2nd object in my JArray. 我尝试在JArray中的每个第二个对象之后添加一个新对象。

I thought about manipulating the JSON data, rather then concrete objects because the received data will most likely be dynamic data. 我考虑过要处理JSON数据,而不要处理具体对象,因为接收到的数据很可能是动态数据。 I'm using the library JObject, but I'm getting some error without any real exception messages. 我正在使用库JObject,但是没有任何真正的异常消息,但出现了一些错误。

My received JSON structure looks like that: 我收到的JSON结构如下所示:

{ "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. 当我尝试向JArray中添加一个placeholderVm时,它第一次运行良好,但是在第二次迭代中,它抛出一个错误而没有异常消息。

Do you know how I can add a new JObject on nth position to my JArray? 您知道如何将第n个位置的新JObject添加到JArray吗?

Thank you! 谢谢!

This is because you are mutating the underlying collection while looping through it in the foreach . 这是因为您正在对基础集合进行变异,同时在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. 这就是为什么您经常会在执行此类操作时看到人们初始化一个新的List<T>以避免该错误的原因。

It actually yields this exception : 实际上会产生此异常:

Run-time exception (line 21): Collection was modified; 运行时异常(第21行):集合已修改; enumeration operation may not execute. 枚举操作可能无法执行。

System.InvalidOperationException: Collection was modified; System.InvalidOperationException:集合已修改; 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 这是一个.NET小提琴

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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