none
wcf and json, method post with array of objects but the objects come null RRS feed

  • Question

  • I am having problem sending post request with a array of objects

    I have a WCF service with the following classes and interfaces:

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Runtime.Serialization;
    using System.ServiceModel;
    using System.ServiceModel.Web;
    using System.Text;
    
    
    namespace WcfService1
    {    
        [ServiceContract]    
        public interface IService1 
        {
            [OperationContract]
            [WebInvoke(Method = "POST", UriTemplate = "/TabelaSalvar", RequestFormat = WebMessageFormat.Json, ResponseFormat = WebMessageFormat.Json, BodyStyle = WebMessageBodyStyle.WrappedRequest)]        
            string Salvar(Tabela entity, string teste);
    
            [OperationContract]
            [WebInvoke(Method = "GET", UriTemplate = "GetData/", ResponseFormat = WebMessageFormat.Json, BodyStyle = WebMessageBodyStyle.Wrapped)]
            string GetData();
    
        }
    
    }
    
    
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Web;
    
    namespace WcfService1
    {
        public class Tabela
        {
            public int Id { get; set; }
            public String Descricao { get; set; }
        }
    }
    
    
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Runtime.Serialization;
    using System.ServiceModel;
    using System.ServiceModel.Web;
    using System.Text;
    
    
    namespace WcfService1
    {
        public class Service1 : IService1
        {
    
            public string Salvar(Tabela entity, string teste)
            {
                string mensagem;
                if (entity == null)
                    mensagem = "entity = null";
                else
                    mensagem = "entity != null";
                if (string.IsNullOrWhiteSpace(teste))
                    mensagem = mensagem + " teste is null or white space";
                else 
                    mensagem = mensagem + " teste is not null or white space";
                return mensagem;
                //return "Descricao: " + entity.Descricao + " ID: " + entity.Id + " teste: " + teste;
            }
    
            public string GetData()
            {
                return "true";
            }
        }
    }

    A console application with following:

    using Newtonsoft.Json;
    using Newtonsoft.Json.Linq;
    using System;
    using System.Collections.Generic;
    using System.IO;
    using System.Linq;
    using System.Net;
    using System.Text;
    using System.Web;
    
    namespace ConsoleApplication1
    {
    
        public static class JsonSerializer
        {
            static string Serialize<T>(T o)
            {
                //   var attr = new JsonObjectAttribute();
                // attr.Title = "Result";
                var jv = JValue.FromObject(o);
                return new JObject(new JProperty("request", jv)).ToString();
            }
    
            public static object JsonPost<T>(T objeto, string uri, string metodo)
            {
                string stringJson = Serialize<T>(objeto); 
                //string stringJson = JsonConvert.SerializeObject(objeto);
                WebClient WC = new WebClient();
                WC.Headers["Content-type"] = "application/json";
                string jsonretorno = WC.UploadString(uri + "/" + metodo, "POST", stringJson);
                return JsonConvert.DeserializeObject(jsonretorno);
            }
    
            public static T JsonGet<T>(string uri, string metodo)
            {
                WebRequest request = WebRequest.Create(uri + "/" + metodo);
                WebResponse ws = request.GetResponse();            
                string jsonString = JObject.Parse(new StreamReader(ws.GetResponseStream(), Encoding.UTF8).ReadToEnd()).First.First.ToString();            
                if (typeof(T).IsGenericType || jsonString.Contains('"'))
                    return JsonConvert.DeserializeObject<T>(jsonString);
                else
                    return JsonConvert.DeserializeObject<T>("\"" + jsonString + "\"");
    
    
            }
        }
    }
    
    
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Web;
    
    namespace ConsoleApplication1
    {
        public class ServiceJson<T>
        {
            private string _uri;
    
            public ServiceJson(string uri)
            {
                _uri = uri;
            }
    
            public string Salvar(T tabela, string teste)
            {
                object[] o = { tabela, teste };            
                return (string)JsonSerializer.JsonPost<object[]>(o, _uri, "TabelaSalvar");
            }
    
            public string GetData()
            {
                return JsonSerializer.JsonGet<string>(_uri, "GetData");
            }
    
        }
    }
    
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Threading.Tasks;
    using WcfService1;
    
    namespace ConsoleApplication1
    {
        class Program
        {
            static void Main(string[] args)
            {
                string uri = @"http://localhost:60474/Service1.svc/";            
                string result = new ServiceJson<string>(uri).GetData();
    
                Tabela t = new Tabela() { Id = 1, Descricao = "TESTE" };
    
                result = new ServiceJson<Tabela>(uri).Salvar(t, "Teste");
            }
        }
    }

    Finally, it is necessary to install Newtonsoft.Json package, through Nuget is: Install-Package Newtonsoft.Json -Version 6.0.7

    download full project link.

    Monday, June 1, 2015 12:30 PM

Answers

  • Hi ratodev,

    I have tested your project and put the breakpoint in the following code:

     public static object JsonPost<T>(T objeto, string uri, string metodo)
            {
                string stringJson = Serialize<T>(objeto); 
    I found the value for the stringJson is:
    {
      "request": [
        {
          "Id": 1,
          "Descricao": "TESTE"
        },
        "Teste"
      ]
    }
    Since your are using this BodyStyle = WebMessageBodyStyle.WrappedRequest, so your request message should use the following format:
    {
      "entity": {
        "Id": 1,
        "Descricao": "TESTE"
      },
      "teste": "Teste"
    }

    So please modify the following code:
    static string Serialize<T>(T o)
            {
                //   var attr = new JsonObjectAttribute();
                // attr.Title = "Result";
                var jv = JValue.FromObject(o);
                return new JObject(new JProperty("request", jv)).ToString();
            }
     public string Salvar(T tabela, string teste)
            {
                object[] o = { tabela, teste };            
                return (string)JsonSerializer.JsonPost<object[]>(o, _uri, "TabelaSalvar");
            }
    To the code below:
    static string Serialize<T>(T o)
            {
                //   var attr = new JsonObjectAttribute();
                // attr.Title = "Result";
                var jv = JValue.FromObject(o);
                return new JObject(new JProperty("entity", jv[0]), new JProperty("teste", jv[1])).ToString();
            }
     public string Salvar(T tabela, string teste)
            {
                object[] o = { tabela, teste };            
                return JsonSerializer.JsonPost<object[]>(o, _uri, "TabelaSalvar").ToString();
            }

    After that it will show the correct result as following:

    For more information, please try to refer to the following article:
    #Difference between WebMessageBodyStyle.Wrapped and WebMessageBodyStyle.Bare:
    http://www.wcf.dotnetarchives.com/2013/12/difference-between-webmessagebodystylew.html .

    Best Regards,
    Amy Peng


    We are trying to better understand customer views on social support experience, so your participation in this interview project would be greatly appreciated if you have time. Thanks for helping make community forums a great place.
    Click HERE to participate the survey.


    Thursday, June 4, 2015 7:58 AM
    Moderator