2

我正在尝试按如下方式构建此 JSON 字符串

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

现在,每当我运行它时,我都会得到 InvalidCastException 未处理/检测到无效 JSON!错误信息。

但是,当我执行以下操作时

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

它工作得很好。

如果有人对如何使这项工作有任何想法或建议,将不胜感激。

谢谢!

4

1 回答 1

4

由于您是手动构建 JSON(实际上不应该这样做),因此您必须确保Message它包含的 JSON 部分包含正确的格式。

string Message = "Hello World";

将导致 JSON 不包含字符串的引号,这是无效的。IE:

{ "message" : Hello World }

您可以手动添加引号,但您应该使用 JSON 库。.NET 在JavaScriptSerializer中有一个简单的。有了它,你可以做这样的事情,而不必担心你是否Message包含正确的格式。

var obj = new { message = "Hello World" };
var serializer = new JavaScriptSerializer();
var json = serializer.Serialize(obj);

push.QueueNotification(new GcmNotification().ForDeviceRegistrationId(RegID)
                                            .WithJson(json));
于 2013-07-29T15:47:26.653 回答