1

我正在尝试将数据发布到 json api。这就是我的代码的样子。它从服务器返回一个错误,那里的人告诉我,我将所有内容作为 json 字符串发送,并且我应该发布只有一个参数是 JSON 搅拌的参数。IE。contact_attributes 应该包含一个字符串,如下所示:

"{\"name\":\"Leigh\",\"surname\":\"Duddy\",\"passport_number\":\" 00000020\",\"unique_identifier\":\"7353280000000020\", \"msisdn\": \"27829042259\",\"bank_account_number\":null,\"bank_account_br anch_code\":null,\"bank_account_branch_name\":null,\"bank_detai ls_required\":false,\"membership_number\ ":null,\"bank_account_b ank_id\":null,\"bank_account_account_type_id\":null,\"bank_account_initials\":null,\"bank_account_surname\":null,\"bank_account_p assport_number\":null,\"date_of_birth \":null,\"debit_day\":null,\"contract_sale_date\":null,\"contract_start_date\":null}"

我完全糊涂了,有谁知道我该怎么做。

public class JsonSaleData
    {
        [DataMember]
        public string contact_attributes { get; set; }
        [DataMember]
        public string campaign_uuid = "9d119cce-25ea-46bc-b7bc-cba7e8323e91";
        [DataMember]
        public string user_credentials = "OCPdNbeltviij8C1RLcf";
        [DataMember]
        public string license_id = "1";

    }

private string PostSaleToClient(string url, JsonSaleData _SaleData)
        {


            string strResult = "";
            try
            {
                ASCIIEncoding encoding = new ASCIIEncoding();


                System.Net.HttpWebRequest httpWebRequest = (HttpWebRequest)System.Net.WebRequest.Create(url);
                httpWebRequest.Method = "POST";
                httpWebRequest.ContentType = "application/json; charset=utf-8";


                DataContractJsonSerializer ser = new DataContractJsonSerializer(typeof(JsonSaleData));
                MemoryStream ms = new MemoryStream();
                ser.WriteObject(ms, _SaleData);
                ms.Position = 0;
                String json = Encoding.UTF8.GetString(ms.ToArray());


                StreamWriter streamWriter = new StreamWriter(httpWebRequest.GetRequestStream());
                streamWriter.Write(json);
                streamWriter.Flush();
                streamWriter.Close();

                System.Net.HttpWebResponse httpWebResp = (HttpWebResponse)httpWebRequest.GetResponse();
                using (var streamReader = new StreamReader(httpWebResp.GetResponseStream()))
                {
                     strResult = streamReader.ReadToEnd();
                }

                return strResult;

            }
            catch (Exception ex)
            {
                string e = ex.Message;
            }

           return strResult;


        }
4

2 回答 2

1

尝试使用以下函数处理 JSON 字符串。

private string ConvertToJSON(objType obj)
  {

string sJSON = "{";

try {
    AppendToJSON(ref sJSON, "obj1Name", obj.obj1);
    AppendToJSON(ref sJSON, "obj2Name", obj.obj2);
    AppendToJSON(ref sJSON, "obj3Name", obj.obj3);
    AppendToJSON(ref sJSON, "obj4Name", obj.obj4);

    return sJSON.Substring(0, sJSON.Length - 1) + "}";

} catch (Exception ex) {
    return "";
}
 }
private void AppendToJSON(ref string byValJSON, string Name, string Value)
  {
byValJSON = byValJSON + "\"" + Name + "\":\"" + Value + "\",";
   }

并将字符串发布到服务器。

using System.Web;

public class AttributesHandler : IHttpHandler
{

public void ProcessRequest(System.Web.HttpContext context)
   {
string JSON = null;
string timeOut = null;

timeOut = System.Web.HttpContext.Current.Server.ScriptTimeout;
try {
    System.Web.HttpContext.Current.Server.ScriptTimeout = 600;
    System.Web.HttpContext.Current.Response.ContentType = "text/javascript";
    System.Web.HttpContext.Current.Response.ContentEncoding = System.Text.Encoding.UTF8;
    JSON = ConvertToJSON(obj);
    System.Web.HttpContext.Current.Response.Write(JSON);

    System.Web.HttpContext.Current.Server.ScriptTimeout = timeOut;

} catch (Exception ex) {
}

   }
   }

调用使用 DotNet 代码:

string Url = "";
Url = "http://xxxxxxxxxxxxxx/AttributesHandler.ashx?cd=xx";
object @out = null;
try {
Net.WebClient webclient = new Net.WebClient();
webclient.UseDefaultCredentials = true;
@out = System.Text.Encoding.ASCII.GetString((webclient.DownloadData(Url)));
} catch (Exception ex) {
//out = ex.InnerException.ToString
}

在这里,他们将仅以字符串形式获得响应。

使用 Javascript Ajax。

$.ajax({
    type: "GET", timeout: 60000, cache: false, dataType: "jsonp", url: "http://xxxxxxxxxxxxxx/AttributesHandler.ashx?cd=xx"         
    success: function (response) {
        objAttributes = response.Attributes; //in object formate
                if (objCardAttributes != null) {
         //can process the objects
               }
                 __doPostBack('upToolkit',);
          },
    error: function (XMLHttpRequest, textStatus, errorThrown) {
        var sReturn = "Please close the browser and relaunch ";
        if (textStatus != null) { sReturn += " Details: (" + textStatus + ")"; }
        if (errorThrown != null) { sReturn += " Description: (" + errorThrown.Description + ")"; }
       __doPostBack('upToolkit', sReturn);
    }
});
于 2013-10-21T07:09:37.757 回答
0

你的json和你的POCO不匹配......没有必要发布多个参数来将数据发送到服务器......但是在这种情况下你的json没有翻译成POCO是问题

"{\"name\":\"Leigh\",\"surname\":\"Duddy\",\"passport_number\":\" 00000020\",\"unique_identifier\":\"7353280000000020\", \"msisdn\": \"27829042259\",\"bank_account_number\":null,\"bank_account_br anch_code\":null,\"bank_account_branch_name\":null,\"bank_detai ls_required\":false,\"membership_number\ ":null,\"bank_account_b ank_id\":null,\"bank_account_account_type_id\":null,\"bank_account_initials\":null,\"bank_account_surname\":null,\"bank_account_p assport_number\":null,\"date_of_birth \":null,\"debit_day\":null,\"contract_sale_date\":null,\"contract_start_date\":null}"

www.json2csharp.com看看你的 json 是不可解析的......

确保你的 json 是正确的..

然后使用此站点创建 csharp 类并反序列化为该特定对象

于 2013-10-21T06:52:59.403 回答