문제

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!

도움이 되었습니까?

해결책

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));
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top