Adding object to JArray overwriting first element

后端 未结 1 1318
滥情空心
滥情空心 2021-01-25 01:09

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.G         


        
相关标签:
1条回答
  • 2021-01-25 01:36

    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.

    0 讨论(0)
提交回复
热议问题