1

My code is below:

string requestBody = string.Format(
             @"{{
                   ""RequestServerVersion"":""2016.04.05"",
                   ""PreferredDate"":""{0}"",
                   ""StaffList"":""{1}""
               }}",
             preferredDate.Date.ToString("yyyy-MM-dd"),
             "test");

StaffList is a string array, If I pass a single string like "test", it won't work. How do I pass a string array to it in the string.Format(...)? Since in the server side, StaffList is handled as a string Array.

Thanks a lot!

1
  • You can convert your array content to JSON string and then pass it to String.Format. See the last answer here Commented Apr 5, 2016 at 5:37

2 Answers 2

2

I would avoid rolling your own JSON when there are good libraries for making sure it works properly.

Try this with Newtonsoft.Json:

string[] staffList = new [] { "Alice", "Bob", "Charlie" };
DateTime preferredDate = DateTime.Now;

var data = new
{
    RequestServerVersion = "2016.04.05",
    PreferredDate = preferredDate.Date.ToString("yyyy-MM-dd"),
    StaffList = staffList,
};

string requestBody = Newtonsoft.Json.JsonConvert.SerializeObject(data);

This outputs:

{
    "RequestServerVersion":"2016.04.05",
    "PreferredDate":"2016-04-05",
    "StaffList":["Alice","Bob","Charlie"]
}

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks Enigmativity. This is helpful.
0

Two things that come into my mind:

  1. Try to join the Array to a single string using string.Join() and split the string on serverside using string.Split()
  2. Use the JSON Arrays Syntax in your code, Loop over each Array index and insert them one by one in this syntax: http://www.w3schools.com/json/json_syntax.asp

BTW: Have you considered to use Serialization instead of building your JSON on your own?

2 Comments

Thanks, Jannik. I will close this question by marking it answered.
Glad I could help.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.