简体   繁体   中英

Converting c# string array to array for json

I have a string array.

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

I need to serialize them as the API is expecting:

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

Here's what I've got right now:

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);

Every example I look at is just a key value pair, but I don't know how to do an array of values to one key.

try SerializeObject and AnonymousType

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");
    //......
}

Define your class like this

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

Then use 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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM