I am trying to iterate (Do While) JSON data input, put Comma after each run, and put [ ] around at the end.
var query = new QueryFunction()
{
Offset = 0,
PageSize = 2
};
do
{
query.Offset = offset;
query.PageSize = pagesize;
Task<OnlineResponse> task = client.Execute(query);
OnlineResponse response = task.Result;
Result result = response.Results[0];
dynamic resultJson = JsonConvert.SerializeObject(result.Data);
offset = pagesize;
resultJsonString = resultJson;
//remaining = result.NumRemaining;
// Tried to put , after each loop
//if (remaining == 0)
// resultJsonString = resultJson;
//else
// resultJsonString = resultJson ",";
} while (offset < 4);
return resultJsonString;
So, currently, the output for "resultJsonString" is like this as it iterate two times:
As you can see, it put [ ] around each run (2 output each time), with no comma after each run.
"[{\"GLDETAIL\":{\"RECORDNO\":\"264378-1756289-919567\",\"BATCH_DATE\":\"02/01/2022\"}},
{\"GLDETAIL\":{\"RECORDNO\":\"264378-1756290-919568-\",\"BATCH_DATE\":\"02/01/2022\"}}]
[{\"GLDETAIL\":{\"RECORDNO\":\"264379-1756291-919569\",\"BATCH_DATE\":\"02/01/2022\"}},
{\"GLDETAIL\":{\"RECORDNO\":\"264379-1756292-919570\",\"BATCH_DATE\":\"02/01/2022\"}}]"
Expected output is like this.
"[{\"GLDETAIL\":{\"RECORDNO\":\"264378-1756289-919567\",\"BATCH_DATE\":\"02/01/2022\"}},
{\"GLDETAIL\":{\"RECORDNO\":\"264378-1756290-919568\",\"BATCH_DATE\":\"02/01/2022\"}},
{\"GLDETAIL\":{\"RECORDNO\":\"264379-1756291-919569\",\"BATCH_DATE\":\"02/01/2022\"}},
{\"GLDETAIL\":{\"RECORDNO\":\"264379-1756292-919570\",\"BATCH_DATE\":\"02/01/2022\"}}]"
CodePudding user response:
Don't append the JSON string manually.
Instead, add the object into the array/list during the iteration in the do-while
loop.
The result.Data
returns an array of data, hence you need List.AddRange()
.
When the loop exits, serialize the array/list.
using Syste.Linq;
List<dynamic> resultList = new List<dynamic>();
do
{
query.Offset = offset;
query.PageSize = pagesize;
Task<OnlineResponse> task = client.Execute(query);
OnlineResponse response = task.Result;
Result result = response.Results[0];
offset = pagesize;
resultList.AddRange(result.Data);
//remaining = result.NumRemaining;
// Tried to put , after each loop
//if (remaining == 0)
// resultJsonString = resultJson;
//else
// resultJsonString = resultJson ",";
} while (offset < 4);
resultJsonString = JsonConvert.SerializeObject(resultList);
return resultJsonString;