Adding object to JArray overwriting first element

佐手、 提交于 2019-12-04 05:01:00

问题


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

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?

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


回答1:


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.

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

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



来源:https://stackoverflow.com/questions/21145017/adding-object-to-jarray-overwriting-first-element

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!