Reputation: 385
im serializing a List of string to a Json string and then generating a File from the json string but for some reason my file doesnt have the "{}" of my json. This is my List Serialization:
List<string> list = new List<string>();
foreach(item in Model){list.Add(item)}
var reqUsers = list;
var json = JsonConvert.SerializeObject(reqUsers);
System.IO.File.WriteAllText(@"\path.txt", json);
My path.txt show this:
["ENS FRUTAS","REST","CENAS","$26.50",0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,"$26.50"]
But i need my output like this:
[["ENS FRUTAS","REST","CENAS","$26.50",0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,"$26.50"]]
My foreach loop to fil my list:
for (int i = 1; i <= 31; i++)
{
var value = 0;
if (item.Fecha.Day == i) { value = item.Cantidad; costo = costo + item.Total; }
total += value;
}
list.Add(item.Descripcion);
list.Add(item.Pdv);
list.Add(item.Rid);
list.Add(((costo / (total + 1)).ToString("C")));
for (int i = 1; i <= 31; i++)
{
var value = 0;
list.Add(value.ToString());
int month = item.Fecha.Month;
if (item.Fecha.Day == i) { value = item.Cantidad; list.Add(value.ToString()); }
}
list.Add(total.ToString());
list.Add((((costo / (total + 1)) * total).ToString("C")));
}
i want each time my list finish a serie of the foreach loop to make the data enclosed by [] How can i do this?
Upvotes: 1
Views: 2196
Reputation: 2143
I am not sure why you need your output to be like that. But if you want it that way, you can do something like this.
List<List<List<string> > > arrayArrayList = new List<List<List<string>>>();
List<List<string>> arrayList = new List<List<string>>();
List<string> list = new List<string>();
list.Add("Hello");
list.Add("Hello1");
list.Add("Hello2");
arrayList.Add(list);
arrayArrayList.Add(arrayList);
list = new List<string>();
list.Add("bye");
list.Add("bye1");
list.Add("bye2");
arrayList = new List<List<string>>();
arrayList.Add(list);
arrayArrayList.Add(arrayList);
var json = JsonConvert.SerializeObject(arrayArrayList);
In this case your output will be [[["Hello","Hello1","Hello2"]],[["bye","bye1","bye2"]]]
Updated the answer based on the recent update to the question.
var buffer = new StringBuilder();
buffer.Append("[");
for(int i=1;i<=10;i++)
{
buffer.Append("[");
foreach(var item in items)
{
buffer.Append("\"\"");
buffer.Append(item.Pro1);
buffer.Append("\"\"",");
//add other props
}
buffer.Append("]");
}
buffer.Append("]");
File.WriteAllText(path,buffer.ToString();
Upvotes: 1
Reputation: 13179
You can wrap your current object being serialized in another collection so that it will be serialized the way you want:
var json = JsonConvert.SerializeObject(new List<object>() { list });
This should put another "[" and "]" around your current serialized text.
Upvotes: 1