使用System从C#集合创建JSON数组.网状物剧本序列化



我有这个代码

            var httpWebRequestAuthentication = (HttpWebRequest)WebRequest.Create("http://api");
        httpWebRequestAuthentication.ContentType = "application/json";
        httpWebRequestAuthentication.Accept = "en";
        httpWebRequestAuthentication.Headers.Add("Accept-Language", "en");
        httpWebRequestAuthentication.Method = "POST";
        using (var streamWriter = new StreamWriter(httpWebRequestAuthentication.GetRequestStream()))
        {
            string json = new JavaScriptSerializer().Serialize(new
            {
                agent_name = "my name",
                agent_password = "myPassword",
                countryCode = "US",
                requestType = "post",
                sales_representatives = new[] { // How do I create here a Foreach loop that will iterate a C# collection and create the JSON array?
                new {
                  product = "agent1",
                  primary_sales_representative= 1234,
                  secondary_sales_representative= 2345
                },
                new {
                  product = "agent2",
                  primary_sales_representative = 1111,
                  secondary_sales_representative= 2222
                }
                }
            });
            streamWriter.Write(json);
            streamWriter.Flush();
            streamWriter.Close();
        }
        var httpResponseAuthentication = (HttpWebResponse)httpWebRequestAuthentication.GetResponse();
        using (var streamReaderAuthentication = new StreamReader(httpResponseAuthentication.GetResponseStream()))
        {
            var resultAuthentication = streamReaderAuthentication.ReadToEnd();
        }

我想更改此代码,这样我的sales_represetatives JSON集合将从我的c#销售代表列表中创建。

我找不到在代码中插入foreach循环来创建JSON数组的方法?

只需替换该代码:

 sales_representatives = new[] { // How do I create here a Foreach loop that will iterate a C# collection and create the JSON array?
            new {
              product = "agent1",
              primary_sales_representative= 1234,
              secondary_sales_representative= 2345
            },
            new {
              product = "agent2",
              primary_sales_representative = 1111,
              secondary_sales_representative= 2222
            }
            }

有以下一个:

sales_representatives = yourCollection.Select(repr=>new {
  product = repr.ProductField,
  primary_sales_representative = repr.PrimaryField,
  secondary_sales_representative = repr.SecondaryField
}

这假设您的c#销售代表列表存储在名为"yourCollection"的集合中,并且该集合中的每个对象都具有ProductField、PrimaryField和SecondaryField属性。根据你的喜好改变。

最新更新