从Web服务返回JSON

时间:2012-07-12 09:29:51

标签: c# asp.net json web-services

上午, 有人可以为我看看这个,看看为什么我只能得到答复

 {"d":"success : False, message  : "}

我希望得到回复。

 {"success" : true, "message" : "***Message Here***"}

以下是我的代码......

 [WebMethod]
    [ScriptMethod(ResponseFormat = ResponseFormat.Json)]
    public string CheckFeedSubmission()
    {
        string responseText = "";
        bool responseSuccess = false;
        try
        {
            aboDataDataContext dc = new aboDataDataContext();

            List<string> id = (from fl in dc.feedLogs where fl.feedStatus == "_SUBMITTED_" select fl.feedSubmissionId).ToList();

            foreach (var submissionId in id)
            {
                try
                {
                    MarketplaceWebServiceConfig config = new MarketplaceWebServiceConfig();

                    config.ServiceURL = "https://mws.amazonservices.co.uk";
                    config.SetUserAgentHeader("twe-amazon-mws", "1.0", "c#");

                    MarketplaceWebService.MarketplaceWebService service = new MarketplaceWebServiceClient(accesskeyID, secretkey, config);

                    GetFeedSubmissionResultRequest request = new GetFeedSubmissionResultRequest();

                    MemoryStream ms = new MemoryStream();

                    request.Merchant = merchantID;
                    request.Marketplace = marketids[0];
                    request.FeedSubmissionId = submissionId;
                    request.FeedSubmissionResult = ms;

                    try
                    {
                        GetFeedSubmissionResultResponse resp = service.GetFeedSubmissionResult(request);

                        if (resp.IsSetGetFeedSubmissionResultResult() == false)
                        {
                            responseText = "IsSetGetFeedSubmissionResultResult=false";
                            responseSuccess = false;
                        }

                        else
                        {
                            StreamReader sr = new StreamReader(ms);
                            string srs = sr.ReadToEnd();

                            XmlDocument doc = new XmlDocument();
                            doc.LoadXml(srs);

                            try
                            {
                                feedLog feedUpdate = dc.feedLogs.Single(l => l.feedSubmissionId == submissionId);
                                feedUpdate.feedStatus = "_" + doc.SelectSingleNode("/AmazonEnvelope/Message/ProcessingReport/StatusCode").InnerText.ToUpper().ToString() + "_";
                                feedUpdate.totalProcessed = Convert.ToInt32(doc.SelectSingleNode("/AmazonEnvelope/Message/ProcessingReport/ProcessingSummary/MessagesProcessed").InnerText);
                                feedUpdate.sucessfulPublish = Convert.ToInt32(doc.SelectSingleNode("/AmazonEnvelope/Message/ProcessingReport/ProcessingSummary/MessagesSuccessful").InnerText);
                                feedUpdate.publishwithErrors = Convert.ToInt32(doc.SelectSingleNode("/AmazonEnvelope/Message/ProcessingReport/ProcessingSummary/MessagesWithError").InnerText);
                                feedUpdate.publishwithWarning = Convert.ToInt32(doc.SelectSingleNode("/AmazonEnvelope/Message/ProcessingReport/ProcessingSummary/MessagesWithWarning").InnerText);
                                feedUpdate.feedResponseXML = doc.InnerXml.ToString();

                                if (doc.SelectSingleNode("/AmazonEnvelope/Message/ProcessingReport/StatusCode").InnerText.ToUpper().ToString() == "COMPLETE")
                                {
                                    try
                                    {
                                        dc.tweProducts.Where(p => p.feedSubmitId == submissionId).ToList().ForEach(i => i.prodPublished = 1);
                                    }
                                    catch (Exception ee) { responseSuccess = false; responseText = "db update tweProducts exception:" + ee.Message; }
                                }

                                dc.SubmitChanges();
                            }
                            catch (Exception ex) { responseSuccess = false; responseText += "\n db update feedLog exception : " + ex.Message; }

                            XDocument pxerror = XDocument.Parse(srs);
                            var results = pxerror.Root.Descendants("Result")
                                          .Where(p => p.Element("ResultCode").Value == "Error");
                            if (results != null)
                            {
                                foreach (var t in results)
                                {
                                    publishError perrors = new publishError();
                                    {
                                        try
                                        {
                                            var resultCode = t.Element("ResultMessageCode").Value;
                                            var resultDescription = t.Element("ResultDescription").Value;
                                            var sku = t.Element("AdditionalInfo").Element("SKU").Value;

                                            perrors.sku = sku;
                                            perrors.errorId = resultCode;
                                            perrors.description = resultDescription;
                                            perrors.feedSubmissionId = submissionId;
                                            perrors.errorResolved = false;

                                            dc.publishErrors.InsertOnSubmit(perrors);
                                            dc.SubmitChanges();
                                        }
                                        catch (Exception ex) { responseSuccess = false; responseText += "db update publishError exception: " + ex.Message; }
                                    }
                                }
                            }

                            #endregion

                            responseSuccess = true;
                            responseText = "Complete";
                        }

                    }
                    catch (Exception ex) { responseSuccess = false; responseText = "GetFeedSubmissionResultResponse error" + ex.Message; }
                }
                catch (MarketplaceWebServiceException ex) { responseSuccess = false; responseText = "starts MarketplaceWebServiceConfig, exception message:" + ex.Message + ",status code:" + ex.StatusCode; }

            }
        }
        catch (Exception ex) { responseSuccess = false; responseText = "starts at aboDataDataContext, exception message:" + ex.Message; }

        return "success : " + responseSuccess + ", message  : " + responseText ;
    }
}

这是我之前提问的后续问题 - How to return JSON from webservice

此外,如果您看到任何改进代码的方法,请告诉我:)

所有的帮助都非常感谢,提前感谢。

2 个答案:

答案 0 :(得分:2)

它因为你返回一个字符串而不是返回一个对象。您想要返回的Json格式表示存在具有2个属性“Success”和“Message”的对象(当您返回简单字符串时)。

首先制作一个将被退回的对象

[DataContract]
public class Message
{
    [DataMember]
    public string Success { get; set; }
    [DataMember]
    public string Message { get; set; }
}

更改方法的签名

    [WebMethod]
    [ScriptMethod(ResponseFormat = ResponseFormat.Json)]
    public Message CheckFeedSubmission()
    {
    .
    .
    }

然后返回此对象

return new Message() { Success = responseSuccess , Message = responseText };

答案 1 :(得分:0)

根据定义,webmethod总是返回一个看起来像这样的json {d:object}其中object是你输入的内容,所以我不认为你可以避免使用“d”

因此您需要返回类似“{”成功“的内容:”true“,”message“:” 此处留言 “}”

不确定它是否会导致语法问题,所以也许你最好还是回复json arr “[{success:true,message:”msg“}]”