将c#字符串数组转换为json的数组

时间:2018-06-05 01:51:47

标签: c# json.net

我有一个字符串数组。

images[0] = 1255nr_171229_620_003_0040.jpg
images[1] = 1255nr_171229_620_003_0061.jpg
images[2] = 1255nr_171229_620_003_0431.jpg
images[3] = 1255nr_171229_620_003_0467.jpg

我需要按API期望序列化它们:

"favorites":["1255nr_171229_620_003_0040.jpg", "1255nr_171229_620_003_0061.jpg", "1255nr_171229_620_003_0431.jpg", ...]

这就是我现在所拥有的:

using Newtonsoft.Json;

HttpClient client = new HttpClient();
client.BaseAddress = new Uri(postURL);
client.DefaultRequestHeaders.Add("Authorization", token);
string POSTcall = string.Format("{{\"name\": \"{0}\",\"email\": \"{1}\",\"phone\": \"{2}\",\"favorites\": \"{9}\"}}", CustomerName, Email, Phone, images[]);

StringContent stringContent = new StringContent(POSTcall, UnicodeEncoding.UTF8, "application/json");
HttpResponseMessage response = await client.PostAsync(new Uri(postURL), stringContent);

我看到的每个示例都只是一个键值对,但我不知道如何为一个键执行值数组。

2 个答案:

答案 0 :(得分:5)

尝试SerializeObjectAnonymousType

void Main()
{
    var CustomerName = "xxx";
    var Email = "xxxx@xxxx";
    var Phone = "88690xxxxxxx";
    var images = new string[]{"1255nr_171229_620_003_0040.jpg","1255nr_171229_620_003_0061.jpg","1255nr_171229_620_003_0431.jpg"};
    string POSTcall= JsonConvert.SerializeObject(new {CustomerName,Email,Phone,favorites=images});
    /*
    result :
        {
            "CustomerName":"xxx","Email":"xxxx@xxxx","Phone":"88690xxxxxxx"
            ,"favorites":["1255nr_171229_620_003_0040.jpg","1255nr_171229_620_003_0061.jpg","1255nr_171229_620_003_0431.jpg"]
        }   
    */
    StringContent stringContent = new StringContent(POSTcall, UnicodeEncoding.UTF8, "application/json");
    //......
}

答案 1 :(得分:3)

像这样定义你的课程

public class Info
{
    public string name { get; set; }
    public string email { get; set; }
    public string phone { get; set; }
    public string[] favorites { get; set; }
}

然后使用JsonConvert

var into = new Info(); 
info.name = "A";
info.email = "a@gmail.com";
info.phone = "000";
info.favorites = images;
var strinContent = Newtonsoft.Json.JsonConvert.SerializeObject(info);