0

I am trying to use OneSignal API. My problem isn't specific to OneSignal but I think that referencing it might make it easier to explain.

OneSignal is an SAAS for delivering notifications to phones and browsers and I am trying to hook it up to my server. The problem is that the request to OneSignal API returns:

{
    "id": "458dcec4-cf53-11e3-add2-000c2940e62c",
    "recipients": 5
}

or

{
    "errors": {
        "invalid_player_ids" : ["5fdc92b2-3b2a-11e5-ac13-8fdccfe4d986", "00cb73f8-5815-11e5-ba69-f75522da5528"]
    }
}

or

{
    "id": "", 
    "recipients": 0, 
    "errors": ["All included players are not subscribed"]
}

while I am trying to deserialize the request using DataContracts and DataContractJsonSerializer.

My question is: how do I parse a JSON where a property can be empty, can be an object or an array of strings? Is there a way to do that using just standard DataContract attributes or do I have to write my own serializer? If so, could you point me to some resources or to any tutorial since I couldn't find anything resolving my problem so far?

dbc
  • 104,963
  • 20
  • 228
  • 340
johnatann
  • 145
  • 11
  • 1
    `DataContractJsonSerializer` is not well suited to parsing implicitly typed polymorphic properties such as the `"errors"` property. Would you consider switching to [tag:json.net]? Even [tag:javascriptserializer] might be easier to use here. – dbc Sep 24 '16 at 16:49
  • I don't mind switching to some other framework but looking at their page I don't see the solution yet. Could you tell me which features of JSON.net should I use for described functionality? – johnatann Sep 24 '16 at 16:54
  • You would use a [custom `JsonConverter`](http://www.newtonsoft.com/json/help/html/CustomJsonConverter.htm). There's no directly equivalent functionality in `DataContractJsonSerializer` because it doesn't offer easy access to the underlying JSON stream -- possibly because it shares a code base with `DataContractSerializer` for XML and Microsoft wanted them to be interchangeable. – dbc Sep 24 '16 at 16:57
  • OK, I've found [link]http://www.newtonsoft.com/json/help/html/SerializingJSONFragments.htm which should do the job. Thank you! – johnatann Sep 24 '16 at 16:58

0 Answers0