使用JSON在Restful WCF服务中接收POST请求的多个对象

时间:2013-11-20 10:10:52

标签: json wcf rest post

将2个对象序列化为流并将其附加到HttpWebRequest

    DataContractJsonSerializer ser = new DataContractJsonSerializer(typeof(OBJECT1));
    ser.WriteObject(stream1, controller);
    ser = new DataContractJsonSerializer(typeof(OBJECT2));
    ser.WriteObject(stream1, reader);
    stream1.position =0;

我的json字符串看起来像这样(在上面的代码之后): {\"Object1Parameter1\":\"2\"}{\"Object2Parameter1\":\"Added reader\",\"Object2Parameter2\":\"2\"}

甚至尝试将父级添加到名为OBJECT1和OBJECT2 resp的此字符串中,但仍未在服务器上反序列化数据。

在Rest服务中接收这样的数据没有问题

[OperationContract]
        [WebInvoke(Method = "POST",
            RequestFormat = WebMessageFormat.Json,
            ResponseFormat = WebMessageFormat.Json,
            BodyStyle = WebMessageBodyStyle.Wrapped,
            UriTemplate = "Controller")]
        string AddBothObjects(/*parameters of both objects listed*/);

如何在服务端以两个对象而不是单个参数接收此数据。 像这样:

[OperationContract]
            [WebInvoke(Method = "POST",
                RequestFormat = WebMessageFormat.Json,
                ResponseFormat = WebMessageFormat.Json,
                BodyStyle = WebMessageBodyStyle.Wrapped,
                UriTemplate = "Controller")]
            string AddBothObjects(Object1 obj1,Object2 obj2);

1 个答案:

答案 0 :(得分:0)

我认为当您将数据发布到WCF服务时,您应该将您发送的所有数据包装到一个对象(1个请求对象)中。这是示例代码,用于显示我正在谈论的内容

客户端:

            // declare ascii encoding
            ASCIIEncoding encoding = new ASCIIEncoding();
            string jsonObject1 = "{\"Object1Parameter1\":\"2\"}";
            string jsonObject2 = "{\"Object2Parameter1\":\"Added reader\",\"Object2Parameter2\":\"2\"}";


            byte[] data = encoding.GetBytes(jsonObject1 + jsonObject2);

            string url = "http://localhost:64273/Sparql.svc/TestForStack";

            string strResult = string.Empty;

            // declare httpwebrequet wrt url defined above
            HttpWebRequest webrequest = (HttpWebRequest)WebRequest.Create(url);
            // set method as post
            webrequest.Method = "POST";
            // set content type
            webrequest.ContentType = "application/x-www-form-urlencoded";
            // set content length
            webrequest.ContentLength = data.Length;
            // get stream data out of webrequest object
            Stream newStream = webrequest.GetRequestStream();

            newStream.Write(data, 0, data.Length);
            newStream.Close();

            //Gets the response
            WebResponse response = webrequest.GetResponse();
            //Writes the Response
            Stream responseStream = response.GetResponseStream();

            StreamReader sr = new StreamReader(responseStream);
            string s = sr.ReadToEnd();

服务接口

[OperationContract]
    [WebInvoke(Method = "POST",
        UriTemplate = "TestForStack",
        RequestFormat = WebMessageFormat.Json,
        ResponseFormat = WebMessageFormat.Json,
        BodyStyle = WebMessageBodyStyle.Bare)]
    Stream TestForStack(Stream request);

服务实施

public Stream TestForStack(Stream request)
    {
        StreamReader requestReader = new StreamReader(request);

        //data contains "{\"Object1Parameter1\":\"2\"}{\"Object2Parameter1\":\"Added reader\",\"Object2Parameter2\":\"2\"}"
        string data = HttpUtility.UrlDecode(requestReader.ReadToEnd());

        //Splits the two json objects into a list of json objects
        var output = data.Split(new[] { '{', '}' }, StringSplitOptions.RemoveEmptyEntries)
              .Select(x => "{" + x + "}")
              .ToList();

        //Parse your json object
        foreach (var entry in output)
        {
            var parsedObject = JsonConvert.DeserializeObject<JObject>(entry);
            foreach (var dataset in parsedObject.Properties())
            {
                Console.WriteLine(dataset.Name);
            }
        }

        byte[] htmlBytes = Encoding.UTF8.GetBytes("Done");

        return new MemoryStream(htmlBytes);
    }