使用System.Web.Script.Serialization

时间:2016-05-10 12:46:47

标签: javascript 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();
        }

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

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

1 个答案:

答案 0 :(得分:1)

只需替换该代码:

 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属性。根据自己的喜好改变。