0

I am sending a message from my C# Windows Service to Amazon Web Services SNS so that it can be received from an iOS application.

PublishRequest pubRequest = new PublishRequest();
pubRequest.TargetArn = arn;

pubRequest.Message = JsonConvert.SerializeObject(myMessage, Formatting.Indented);
pubRequest.MessageStructure = "json";

When I use JsonConvert.SerializeObject this produces a mesage string like so:

{"default":"My Message.  ","APNS":{"aps":{"alert":{"title":"My Title","body":"MyBody data"},"data":{"someDataTolookAt":"blahblah"}}}}

BUT I need the quotes in the APNS part to be escaped like so:

{"default":"My Message.  ","APNS":{\"aps\":{\"alert\":{\"title\":\"My Title\","body\":\"MyBody data\"},\"data\":{\"someDataTolookAt\":\"blahblah\"}}}}

How can I do this?

Panagiotis Kanavos
  • 120,703
  • 13
  • 188
  • 236
Harry Boy
  • 4,159
  • 17
  • 71
  • 122
  • 2
    Write your own JSON converter. [See example here](https://www.newtonsoft.com/json/help/html/CustomJsonConverter.htm) – Oram Sep 27 '18 at 10:20
  • 1
    [Also see this](https://stackoverflow.com/questions/36474609/c-sharp-format-json-with-backslash-in-value/36474971) – Hary Sep 27 '18 at 10:21
  • I'm just curious... Why would you need a serialized format like that? That's even not a valid json. Did you mean you want APNS part to be a string instead of an object? – Alan haha Sep 27 '18 at 10:33
  • For some reason AWS is only forwarding the default part of the message and not the APNS part. From this example I believe that back slashes are required https://docs.aws.amazon.com/sns/latest/dg/SNSMobilePushAPNSAPI.html – Harry Boy Sep 27 '18 at 10:42
  • @HarryBoy if you look more carefully docs provide valid json with quotes around { and } – Access Denied Sep 27 '18 at 10:48
  • "APNS_SANDBOX":"{ \"aps\" : { \"alert\" : \"You have got email.\", \"badge\" : 9,\"sound\" :\"default\"}}" – Access Denied Sep 27 '18 at 10:48

1 Answers1

2

In fact API expects APNS serialized as string, not as json and you need to convert its value to json string. Create custom JSON converter for this particular property.

[JsonConverter(typeof(MyJsonConverter))]
someclass APNS {get;set;}

This converter will also do JsonConvert.SerializeObject(APNSobject) => hence your json will have escaped string for apns object.

Access Denied
  • 8,723
  • 4
  • 42
  • 72