Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • Home
  • SEARCH
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 8665885
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 12, 20262026-06-12T17:35:37+00:00 2026-06-12T17:35:37+00:00

I’m trying to consume a RESTful JSON web service using WCF on the client

  • 0

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.

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-12T17:35:38+00:00Added an answer on June 12, 2026 at 5:35 pm

    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();
        }
    }
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

That's pretty much it. I'm using Nokogiri to scrape a web page what has
I'm trying to decode HTML entries from here NYTimes.com and I cannot figure out
Seemingly simple, but I cannot find anything relevant on the web. What is the
I am trying to understand how to use SyndicationItem to display feed which is
Basically, what I'm trying to create is a page of div tags, each has
I'm new to using the Perl treebuilder module for HTML parsing and can't figure
link Im having trouble converting the html entites into html characters, (&# 8217;) i
I have a string like this: La Torre Eiffel paragonata all&#8217;Everest What PHP function
I am reading a book about Javascript and jQuery and using one of the
I am trying to render a haml file in a javascript response like so:

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.