1

I'm trying to consume a RESTful JSON web service using WCF on the client side. The service is 3rd party, so I cannot make any changes to the server response.

The server is sending back a response that looks something like this when there's only one data point...

Single Data Point

{
  "Data":
  {
    "MyPropertyA":"Value1",
    "MyPropertyB":"Value2"
  },
}

and something like this when there's more than one data point...

Multiple Data Points

{
  "Data":
  [
    {
      "MyPropertyA":"Value1",
      "MyPropertyB":"Value2"
    },
    {
      "MyPropertyA":"Value3",
      "MyPropertyB":"Value4"
    },
    {
      "MyPropertyA":"Value5",
      "MyPropertyB":"Value6"
    }
  ],
}

I have my service contract set up like this...

[ServiceContract]
public interface IRewardStreamService
{
    [OperationContract]
    [WebInvoke]
    MyResponse GetMyStuff();
}

and a data point's data contract like this...

[DataContract]
public class MyData
{
  [DataMember]
  public string MyPropertyA { get; set; }

  [DataMember]
  public string MyPropertyB { get; set; }
}

and the only way I can get the single data point response to work is if I have a single instance property like this, but this does not parse the multiple data point response...

Response for Single Instance

[DataContract]
public class MyResponse
{
  [DataMember]
  public MyData Data { get; set; }
}

and the only way I can get the multiple data point response to work is if I have an array / list instance property like this, but this does not parse the single data point response...

Response for Multiple Instance

[DataContract]
public class MyResponse
{
  [DataMember]
  public IList<MyData> Data { get; set; }
}

I understand the issue is that the response is omitting the brackets when there's only one data point returned, but it seems that WCF doesn't play well with deserializing that syntax. Is there some way I can tell the DataContractJsonSerializer to allow single element arrays to not include brackets and then tell my service to use that serializer? Maybe a service behavior or something?

Any direction would be helpful.

TylerOhlsen
  • 5,485
  • 1
  • 24
  • 39
  • You could try using Javascript deserializer rather than Datacontractjsonserializer. Also refer to this link: http://stackoverflow.com/questions/596271/deserialization-problem-with-datacontractjsonserializer – Rajesh Oct 11 '12 at 09:10
  • Also you can go through this nice article that explains on how you can use the serializer to deserialize your json string: http://www.codeproject.com/Articles/272335/JSON-Serialization-and-Deserialization-in-ASP-NET – Rajesh Oct 11 '12 at 09:12
  • @Rajesh, do you know of a way to inject the Javascript Deserializer into the WCF pipeline in place of the DataContractJsonSerializer? – TylerOhlsen Oct 11 '12 at 18:21
  • Please refer to this link that might give you some insight on how you can integrate a different serializer to the WCF pipeline: http://weblogs.thinktecture.com/cweyer/2010/12/using-jsonnet-as-a-default-serializer-in-wcf-httpwebrest-vnext.html – Rajesh Oct 12 '12 at 11:52

2 Answers2

1

You can use a custom message formatter to change the deserialization of the JSON into the data contract you want. In the code below, the data contract is defined to have a List<MyData>; if the response contains only one data point, it will "wrap" that into an array prior to passing to the deserializer, so it will work for all cases.

Notice that I used the JSON.NET library to do the JSON modification, but that's not a requirement (it just has a nice JSON DOM to work with the JSON document).

public class StackOverflow_12825062
{
    [ServiceContract]
    public class Service
    {
        [WebGet]
        public Stream GetData(bool singleDataPoint)
        {
            string result;
            if (singleDataPoint)
            {
                result = @"{ 
                  ""Data"": 
                  { 
                    ""MyPropertyA"":""Value1"", 
                    ""MyPropertyB"":""Value2"" 
                  }, 
                }";
            }
            else
            {
                result = @"{ 
                  ""Data"": 
                  [ 
                    { 
                      ""MyPropertyA"":""Value1"", 
                      ""MyPropertyB"":""Value2"" 
                    }, 
                    { 
                      ""MyPropertyA"":""Value3"", 
                      ""MyPropertyB"":""Value4"" 
                    }, 
                    { 
                      ""MyPropertyA"":""Value5"", 
                      ""MyPropertyB"":""Value6"" 
                    } 
                  ], 
                } ";
            }

            WebOperationContext.Current.OutgoingResponse.ContentType = "application/json";
            return new MemoryStream(Encoding.UTF8.GetBytes(result));
        }
    }
    [DataContract]
    public class MyData
    {
        [DataMember]
        public string MyPropertyA { get; set; }

        [DataMember]
        public string MyPropertyB { get; set; }
    }
    [DataContract]
    public class MyResponse
    {
        [DataMember]
        public List<MyData> Data { get; set; }

        public override string ToString()
        {
            return string.Format("MyResponse, Data.Length={0}", Data.Count);
        }
    }
    [ServiceContract]
    public interface ITest
    {
        [WebGet]
        MyResponse GetData(bool singleDataPoint);
    }
    public class MyResponseSingleOrMultipleClientReplyFormatter : IClientMessageFormatter
    {
        IClientMessageFormatter original;
        public MyResponseSingleOrMultipleClientReplyFormatter(IClientMessageFormatter original)
        {
            this.original = original;
        }

        public object DeserializeReply(Message message, object[] parameters)
        {
            WebBodyFormatMessageProperty messageFormat = (WebBodyFormatMessageProperty)message.Properties[WebBodyFormatMessageProperty.Name];
            if (messageFormat.Format == WebContentFormat.Json)
            {
                MemoryStream ms = new MemoryStream();
                XmlDictionaryWriter jsonWriter = JsonReaderWriterFactory.CreateJsonWriter(ms);
                message.WriteMessage(jsonWriter);
                jsonWriter.Flush();
                string json = Encoding.UTF8.GetString(ms.ToArray());
                JObject root = JObject.Parse(json);
                JToken data = root["Data"];
                if (data != null)
                {
                    if (data.Type == JTokenType.Object)
                    {
                        // single case, let's wrap it in an array
                        root["Data"] = new JArray(data);
                    }
                }

                // Now we need to recreate the message
                ms = new MemoryStream(Encoding.UTF8.GetBytes(root.ToString(Newtonsoft.Json.Formatting.None)));
                XmlDictionaryReader jsonReader = JsonReaderWriterFactory.CreateJsonReader(ms, XmlDictionaryReaderQuotas.Max);
                Message newMessage = Message.CreateMessage(MessageVersion.None, null, jsonReader);
                newMessage.Headers.CopyHeadersFrom(message);
                newMessage.Properties.CopyProperties(message.Properties);
                message = newMessage;
            }

            return this.original.DeserializeReply(message, parameters);
        }

        public Message SerializeRequest(MessageVersion messageVersion, object[] parameters)
        {
            throw new NotSupportedException("This formatter only supports deserializing reply messages");
        }
    }
    public class MyWebHttpBehavior : WebHttpBehavior
    {
        protected override IClientMessageFormatter GetReplyClientFormatter(OperationDescription operationDescription, ServiceEndpoint endpoint)
        {
            IClientMessageFormatter result = base.GetReplyClientFormatter(operationDescription, endpoint);
            if (operationDescription.Messages[1].Body.ReturnValue.Type == typeof(MyResponse))
            {
                return new MyResponseSingleOrMultipleClientReplyFormatter(result);
            }
            else
            {
                return result;
            }
        }
    }
    public static void Test()
    {
        string baseAddress = "http://" + Environment.MachineName + ":8000/Service";
        WebServiceHost host = new WebServiceHost(typeof(Service), new Uri(baseAddress));
        host.Open();
        Console.WriteLine("Host opened");

        ChannelFactory<ITest> factory = new ChannelFactory<ITest>(new WebHttpBinding(), new EndpointAddress(baseAddress));
        factory.Endpoint.Behaviors.Add(new MyWebHttpBehavior());
        ITest proxy = factory.CreateChannel();

        Console.WriteLine(proxy.GetData(false));
        Console.WriteLine(proxy.GetData(true));

        Console.Write("Press ENTER to close the host");
        ((IClientChannel)proxy).Close();
        factory.Close();
        Console.ReadLine();
        host.Close();
    }
}
carlosfigueira
  • 85,035
  • 14
  • 131
  • 171
  • Exactly the kind of solution I was looking for. Thanks so much for posting such an excellent and easy to read/understand answer! – TylerOhlsen Oct 14 '12 at 06:57
0

I don't know about using WCF so I'll change to Asp.Net WCF. Here is an article that will get you one the way

http://www.west-wind.com/weblog/posts/2012/Aug/30/Using-JSONNET-for-dynamic-JSON-parsing

I just can't figure out how to determine if it's an array or a single object. Here is a little code.

    [TestMethod]
    public void SingleObject()
    {
        using (var client = new HttpClient())
        {
            var result = client.GetStringAsync("http://localhost:8080/api/JSONTestOne");
            string content = result.Result;
            JObject jsonVal = JObject.Parse(content);
            dynamic aFooObj = jsonVal;
            Console.WriteLine(aFooObj.afoo.A);
        }
    }

    [TestMethod]
    public void ArrayWithObject()
    {
        using (var client = new HttpClient())
        {
            var result = client.GetStringAsync("http://localhost:8080/api/JSONTest");
            string content = result.Result;
            JObject jsonVal = JObject.Parse(content);
            dynamic foos = jsonVal;
            Console.WriteLine(foos[0].A);
        }
    }
suing
  • 2,808
  • 2
  • 16
  • 18
  • I was really wanting to stick with using WCF. Also, I would prefer to not add another external dependency to my project. – TylerOhlsen Oct 11 '12 at 04:34
  • In that case. I would make the request and get the string using the WebRequest object. Then parse it to determine what contract to use to deserialize it. There might be a way to get that into WCF pipeline, but I'm not sure how. – suing Oct 11 '12 at 09:17