-2

I am trying to create a json string to send via a httprequest, I have json string like so:

{
    "a-string": "123",
    "another-string": "hello",
    "another": "1"
}

My problem is, if I try and generate it like so

 string json = new JavaScriptSerializer().Serialize(new
    {
    "a-string" = "123",
    "another-string" = "hello",
    "another" = "1"
    });

Leads to:enter image description here

So what is a way of trying to do the above, without getting that error?

Uwe Keim
  • 39,551
  • 56
  • 175
  • 291
4334738290
  • 393
  • 2
  • 19
  • 1
    [Possible duplicate](http://stackoverflow.com/questions/12456075/changing-property-names-for-serializing) – Max May 20 '17 at 19:01
  • 1
    [Possible duplicate](http://stackoverflow.com/questions/12456075/changing-property-names-for-serializing) – Max May 20 '17 at 19:02

1 Answers1

0

Use Json NewtonSoft NuGet package. Then use my answer here to create a C# class for you json. Since your json has names in them which are not allowed as property names in C#, you can use the JsonPropety attribute so it can use it during serialization. Here is all of the code:

public class Rootobject
{
    [JsonProperty("a-string")]
    public string astring { get; set; }

    [JsonProperty("another-string")]
    public string anotherstring { get; set; }
    public string another { get; set; }
}

public class Program
{
    public static void Main()
    {
        var root = new Rootobject { another = "1", anotherstring = "hello", astring = "123" };
        string json = JsonConvert.SerializeObject(root);

        Console.Read();
    }
}
Community
  • 1
  • 1
CodingYoshi
  • 25,467
  • 4
  • 62
  • 64