C#中将foreach改为for循环,并将数据添加到数组中以["",""]格式输出
程序员文章站
2024-03-24 22:43:40
...
如何反序列化为对象具体步骤见:将json带数组的数据反序列化
将List数据添加到数组中,然后将数组以[“”,”“]格式输出:
类似这里的id(多个放到数组中)
public class OrderList
{
public bool success { get; set; }
public List<ModelOrder> model { get; set; }
public int total { get; set; }
}
public class ModelOrder
{
public string id { get; set; }
public string code { get; set; }
public string entityId{ get; set; }
public string name{ get; set; }
public string price{ get; set; }
public int kind { get; set; }
public string kindName{ get; set; }
}
public static String test(string jsonStr)
{
System.Web.Script.Serialization.JavaScriptSerializer js = new System.Web.Script.Serialization.JavaScriptSerializer();
Test.OrderList orderList = js.Deserialize<Test.OrderList>(jsonStr);
if(orderList.success)
{
List<Test.ModelOrder> modelOrder = orderList.model;
//将这个列表中的orderId直接添加到数组中
string[] array = new string[modelOrder.Count];//创建数组
string resArr="";
for (int i=0;i< modelOrder.Count;i++)//以for方式
{
Test.ModelOrder item = modelOrder[i];//foreach 与for的互转
String orderIdOrder = item.orderVo.orderId;
array[i] = orderIdOrder.ToString();
resArr = string.Join("\",\"", (string[])array.ToArray() ); //\"" + ticket+"\"
//.ToArray(typeof(string)));
}
string arrStr = "[\"" + resArr + "\"]";//将数据转为数组["",""]格式输出
System.Diagnostics.Debug.WriteLine("订单列表直接toString为:" + array.ToString());
System.Console.WriteLine("");
System.Console.WriteLine("数组结构为:"+ arrStr);
//foreach的方式为:
foreach (Test.ModelOrder item in modelOrder)
{
String orderIdOrder = item.orderVo.orderId;
}
}
运行结果为: