将对象添加到JArray覆盖第一个元素 [英] Adding object to JArray overwriting first element

查看:48
本文介绍了将对象添加到JArray覆盖第一个元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

将新对象添加到JArray时,每个对象都将添加到数组([0])的第一个条目中,并附加到数组中.

When adding a new object to a JArray each object is added to the first entry in the array ([0]) along with being appended to the array.

    response = client.GetAsync(new Uri(urlIndexDoc)).Result;
    result = response.Content.ReadAsStringAsync().Result; 

    JObject OPDDoc = JObject.Parse(result);
    JArray indexCEM = new JArray();
    JObject oNew = new JObject();  

    int idxcount = Convert.ToInt32(ConfigurationManager.AppSettings["IndexCount"]) + 1;  

   for (int i = 1; i < idxcount ; i++)
       {
           string istring = i.ToString();
           var idxname = OPDDoc["IndexName_" + istring];
           if (idxname != null)
           {
               oNew["PriceIndexId"] = istring;
               oNew["IndexName"] = idxname;
               oNew["IndexPrice"] = OPDDoc["IndexPrice_" + istring];
               indexCEM.Add(oNew);
            }
       }

每次添加下一个对象时,我都可以看到它覆盖了调试器中的第一个元素.结果是附加的最后一项以及最后一项都以indexCEM [0]结尾.我在这里缺少什么还是这是一个错误?

I can watch it overwrite the first element in the debugger each time the next object is added. The result is that the last item appended ends up in indexCEM[0] as well as being the last item. Am I missing something here or is this a bug?

在控制台应用程序中使用VS 2013和Json.Net 5.08.

Using VS 2013 and Json.Net 5.08 in a console app.

推荐答案

问题是您正在循环外创建oNew JObject,然后重用该实例,并在每次迭代中将其重新添加到JArray中.环形.由于JArray具有对同一个JObject实例的多个引用,因此,当您更改该实例时,它会在数组中的多个位置反映出来也就不足为奇了.

The problem is that you are creating the oNew JObject outside the loop, then reusing that instance and re-adding it to the JArray in each iteration of the loop. Since the JArray has multiple references to the same JObject instance, it's no surprise that when you change that instance, it will be reflected in multiple places in the array.

您需要做的是像这样在循环内移动oNew的创建:

What you need to do is move the creation of oNew inside the loop like this:

for (int i = 1; i < idxcount ; i++)
{
    string istring = i.ToString();
    var idxname = OPDDoc["IndexName_" + istring];
    if (idxname != null)
    {
        JObject oNew = new JObject();  
        oNew["PriceIndexId"] = istring;
        oNew["IndexName"] = idxname;
        oNew["IndexPrice"] = OPDDoc["IndexPrice_" + istring];
        indexCEM.Add(oNew);
    }
}

然后,将在循环的每次迭代中创建一个新的JObject,并且您将不再覆盖值.

Then a new JObject will be created in each iteration of the loop, and you will no longer be overwriting your values.

这篇关于将对象添加到JArray覆盖第一个元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆