-2

I'm getting an exception "Input string was not in a correct format". I don't understand why. I looked at the documentation, but that didn't give me any ideas.

       string body = string.Format(@"{
                          ""credentials"": {
                                        ""name"": ""{0}"",
                                        ""password"": ""{1}"",
                                        ""site"": {
                                        ""contentUrl"": ""{2}""
                                                  }
                                            }
                                }",Username, Password, siteName);

Not enough sleep and old code... I was deserializing the response but not serializing the request ‍♂️

ThomasRones
  • 657
  • 8
  • 29
  • 3
    For JSON parsing/serialization just use [Newtonsoft.Json](https://www.nuget.org/packages/Newtonsoft.Json/) – Maximilian Ast Jun 26 '19 at 12:36
  • It think it's due to all the extra { and } from the JSON data. – Tony Abrams Jun 26 '19 at 12:36
  • 1
    `I looked at the documentation` - please have [another look](https://learn.microsoft.com/en-us/dotnet/api/system.string.format?view=netframework-4.8#how-do-i-include-literal-braces--and--in-the-result-string). – GSerg Jun 26 '19 at 12:37
  • 2
    Put the data into an object and then JSON serialise it rather than use string concatenation. – mjwills Jun 26 '19 at 12:37

1 Answers1

0

{ and } have special meanings in a format string. If you want the string to contain them literally, you have to escape them by doubling them:

string body = string.Format(@"{{
 ""credentials"": {{
               ""name"": ""{0}"",
               ""password"": ""{1}"",
               ""site"": {{
               ""contentUrl"": ""{2}""
                         }}
                   }}
       }}", Username, Password, siteName);

Alternatively, as @mjwills has suggested, you can create an anonymous object and serialize this to JSON:

var obj = new { name = Username, password = Password, site = new { contentUrl = siteName }};
string body = new JavaScriptSerializer().Serialize(obj);