0

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.

1
  • 1
    Tip: An array in JSON can be represented by an IEnumerable, List or Array in C#. Also, you shouldn't build your JSON as a string, especially not when you're already referencing JSON.Net. Commented Jun 5, 2018 at 2:06

2 Answers 2

4

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");
    //......
}
Sign up to request clarification or add additional context in comments.

2 Comments

This looks nice and clean. Going to make the changes. By doing it this way do I still need the line StringContent stringContent = new StringContent(POSTcall, UnicodeEncoding.UTF8, "application/json");
@MattWiner i add.
3

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 = "[email protected]";
info.phone = "000";
info.favorites = images;
var strinContent = Newtonsoft.Json.JsonConvert.SerializeObject(info);

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.