Search code examples
c#jsonpushsharp

C# .WithJson Invalid JSON Error


I'm trying to build this JSon string as follows

push.QueueNotification(new GcmNotification().ForDeviceRegistrationId(RegID)
                                  .WithJson(@"{""message"":"+Message+"}"));

Now whenever I run this, I get the InvalidCastException was unhandled/Invalid JSON detected! error message.

However when I do the following

push.QueueNotification(new GcmNotification().ForDeviceRegistrationId(RegID)
                                  .WithJson(@"{""message"":""Hello World""}"));

It works perfectly fine.

If anyone has any ideas or suggestions on how to get this working it would be greatly appreciated.

Thanks!


Solution

  • Since you're manually constructing your JSON (which you shouldn't do, really), you have to ensure Message contains the proper formatting for the portion of the JSON it contains.

    string Message = "Hello World";
    

    will result in JSON that doesn't include quotes around a string, which is invalid. Ie:

    { "message" : Hello World }
    

    You could add quotes manually, but what you should do is use a JSON library. .NET has a simple one in JavaScriptSerializer. With it you can do something like this and never worry about whether your Message contains the proper formatting.

    var obj = new { message = "Hello World" };
    var serializer = new JavaScriptSerializer();
    var json = serializer.Serialize(obj);
    
    push.QueueNotification(new GcmNotification().ForDeviceRegistrationId(RegID)
                                                .WithJson(json));