Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/typescript/8.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 如何创建多级json并将其作为web请求传递?_C#_Json_Httpwebrequest - Fatal编程技术网

C# 如何创建多级json并将其作为web请求传递?

C# 如何创建多级json并将其作为web请求传递?,c#,json,httpwebrequest,C#,Json,Httpwebrequest,我正试图连接到一个api并向其传递一个json请求。我不确定如何格式化json数据,所以我找到了一篇建议使用json2csharp.com的帖子 因此,我用于创建json请求数据所需的类: curl -v -X POST \ -H "Authorization: APIKEY" \ -H "Content-Type: application/json" \ -d '{ "type": "sale", "amount": 1112, "tax_amount":

我正试图连接到一个api并向其传递一个json请求。我不确定如何格式化json数据,所以我找到了一篇建议使用json2csharp.com的帖子

因此,我用于创建json请求数据所需的类:

curl -v -X POST \
  -H "Authorization: APIKEY" \
  -H "Content-Type: application/json" \
  -d '{
    "type": "sale",
    "amount": 1112,
    "tax_amount": 100,
    "shipping_amount": 100,
    "currency": "USD",
    "description": "test transaction",
    "order_id": "someOrderID",
    "po_number": "somePONumber",
    "ip_address": "4.2.2.2",
    "email_receipt": false,
    "email_address": "user@home.com",
    "create_vault_record": true,
    "payment_method": {
        "card": {
          "entry_type": "keyed",
          "number": "4012000098765439",
          "expiration_date": "12/20",
          "cvc": "999",
          "cardholder_authentication": {
            "condition": "...",
            "eci": "...",
            "cavv": "...",
            "xid": "...",
          }
        }
        ... or ...
        "customer": {
          "id": "b798ls2q9qq646ksu070",
          "payment_method_type": "card",
          "payment_method_id": "b798ls2q9qq646ksu080",
          "billing_address_id": "b798ls2q9qq646ksu07g",
          "shipping_address_id": "b798ls2q9qq646ksu07g"
        }
        ... or ...
        "terminal": {
          "id": "<terminal id>"
          "expiration_date": "12/20",
          "cvc": "999",
          "print_receipt": "both"
          "signature_required": true
        }
        ... or ...
        "token": "<tokenizer token goes here>",
        ... or ...
        "ach": {
          "routing_number": "490000018",
          "account_number": "999999", 
          "sec_code": "ccd",
          "account_type": "checking",
          "check_number":"1223",
          "accountholder_authentication": {
            "dl_state": "IL",
            "dl_number": "r500123123"
          }
          ... or ...
        "apm": {
          "type": "alipay",
          "merchant_redirect_url": "http://merchantwebsite.com/",
          "locale": "en-US",
          "mobile_view": false
        }
      }
    },
    "billing_address" : {
        "first_name": "John",
        "last_name": "Smith",
        "company": "Test Company",
        "address_line_1": "123 Some St",
        "city": "Wheaton",
        "state": "IL",
        "postal_code": "60187",
        "country": "US",
        "phone": "5555555555",
        "fax": "5555555555",
        "email": "help@website.com"
    },
    "shipping_address" : {
        "first_name": "John",
        "last_name": "Smith",
        "company": "Test Company",
        "address_line_1": "123 Some St",
        "city": "Wheaton",
        "state": "IL",
        "postal_code": "60187",
        "country": "US",
        "phone": "5555555555",
        "fax": "5555555555",
        "email": "help@website.com"
    }
}'   \
"URL_GOES_HERE/transaction"
以下是我目前的代码:

private void button1_Click(object sender, EventArgs e)
{
  var urlx = "https://xxxxx.xxxxxxx.com/api/";
  var usr = "xxxxxxxxxxx";
  var pwd = "xxxx";

  // replace with the TEST class to pass in the required JSON request
  // BaSysRequest item = new BaSysRequest();
  // item.username = usr;
  // item.password = pwd;

  string request = JsonConvert.SerializeObject(item);

  Uri url = new Uri(string.Format(urlx));

  string response = Post(url, request);

  if (response != null)
  {
    Console.WriteLine(response);
  }
  else
  {
    Console.WriteLine("nothing");

  }

}


public string Post(Uri url, string value)
{
  var request = HttpWebRequest.Create(url);
  var byteData = Encoding.ASCII.GetBytes(value);
  request.ContentType = "application/json";
  request.Method = "POST";

  try
  {
    using (var stream = request.GetRequestStream())
    {
      stream.Write(byteData, 0, byteData.Length);
    }
    var response = (HttpWebResponse)request.GetResponse();
    var responseString = new StreamReader(response.GetResponseStream()).ReadToEnd();

    return responseString;
  }
  catch (WebException e)
  {
    return null;
  }
}

public string Get(Uri url)
{
  var request = HttpWebRequest.Create(url);
  request.ContentType = "application/json";
  request.Method = "GET";

  try
  {
    var response = (HttpWebResponse)request.GetResponse();
    var responseString = new StreamReader(response.GetResponseStream()).ReadToEnd();

    return responseString;
  }
  catch (WebException e)
  {
    return null;
  }
}
如何在类中填充ApiRequest和pass?我是否为json数据正确创建了类


有什么建议吗?

因为付款方式可以是不同的类型,所以可以利用泛型

public class TransactionRequest<T> {
    public string type { get; set; }
    public long amount { get; set; }
    public long tax_amount { get; set; }
    public long shipping_amount { get; set; }
    public string currency { get; set; }
    public string description { get; set; }
    public string order_id { get; set; }
    public string po_number { get; set; }
    public string ip_address { get; set; }
    public bool email_receipt { get; set; }
    public string email_address { get; set; }
    public bool create_vault_record { get; set; }
    public Dictionary<string, T> payment_method { get; set; }
    public Address billing_address { get; set; }
    public Address shipping_address { get; set; }
}

public class Address {
    public string first_name { get; set; }
    public string last_name { get; set; }
    public string company { get; set; }
    public string address_line_1 { get; set; }
    public string address_line_2 { get; set; }
    public string city { get; set; }
    public string state { get; set; }
    public string postal_code { get; set; }
    public string country { get; set; }
    public string phone { get; set; }
    public string fax { get; set; }
    public string email { get; set; }
}
从这里开始,只需构造请求并发布到所需的URL

比如说

public partial class Card {
    public string entry_type { get; set; }
    public string number { get; set; }
    public string expiration_date { get; set; }
    public long cvc { get; set; }
    public CardholderAuthentication cardholder_authentication { get; set; }
}

public partial class CardholderAuthentication {
    public string condition { get; set; }
    public string eci { get; set; }
    public string cavv { get; set; }
    public string xid { get; set; }
}
static Lazy<HttpClient> client = new Lazy<HttpClient>();

private async void button1_Click(object sender, EventArgs e) {
    var urlx = "https://xxxxx.xxxxxxx.com/api/";
    var usr = "xxxxxxxxxxx";
    var pwd = "xxxx";

    Card card = new Card();
    //populate as needed

    TransactionRequest<Card> item = new TransactionRequest<Card>();
    //populate as needed

    //set payment method accordingly
    item.payment_method["card"] = card;

    Uri url = new Uri(string.Format(urlx));

    string response = await PostAsync(url, item);
    if (response != null) {
        Console.WriteLine(response);
    } else {
        Console.WriteLine("nothing");
    }
}

public async Task<string> PostAsync<T>(Uri url, T value) {
    try {
        string json = JsonConvert.SerializeObject(value);
        var content = new StringContent(json, System.Text.Encoding.UTF8, "application/json");
        var response = await client.Value.PostAsync(url, content);
        var responseString = await response.Content.ReadAsStringAsync();
        return responseString;
    } catch (Exception e) {
        //TODO: log error
        return null;
    }
}
static Lazy client=new Lazy();
私有异步无效按钮1\u单击(对象发送方,事件参数e){
var urlx=”https://xxxxx.xxxxxxx.com/api/";
var usr=“xxxxxxxxxx”;
var pwd=“xxxx”;
卡片=新卡片();
//根据需要填充
TransactionRequest项=新建TransactionRequest();
//根据需要填充
//设置相应的付款方式
项目.付款方式[“卡”]=卡;
uriurl=新的Uri(string.Format(urlx));
字符串响应=等待PostAsync(url,项目);
if(响应!=null){
控制台写入线(响应);
}否则{
Console.WriteLine(“无”);
}
}
公共异步任务PostAsync(Uri url,T值){
试一试{
字符串json=JsonConvert.SerializeObject(值);
var content=newstringcontent(json,System.Text.Encoding.UTF8,“application/json”);
var response=wait client.Value.PostAsync(url、内容);
var responseString=await response.Content.ReadAsStringAsync();
回报率;
}捕获(例外e){
//TODO:日志错误
返回null;
}
}

下面是一种使用HttpClient快速发布帖子的肮脏方法:

    private HttpResponseMessage Post(string url, string path, object content)
    {
        string serialized = JsonConvert.SerializeObject(content);
        StringContent stringContent = new StringContent(serialized, Encoding.UTF8, "application/json");

        HttpClient client = new HttpClient();
        client.BaseAddress = new Uri(url);
        HttpResponseMessage response = Task.Run(() => client.PostAsync(path, stringContent)).Result;
        client.Dispose();

        return response;
    }

没有限制,我知道url和requestUri之间的区别是什么?
    private HttpResponseMessage Post(string url, string path, object content)
    {
        string serialized = JsonConvert.SerializeObject(content);
        StringContent stringContent = new StringContent(serialized, Encoding.UTF8, "application/json");

        HttpClient client = new HttpClient();
        client.BaseAddress = new Uri(url);
        HttpResponseMessage response = Task.Run(() => client.PostAsync(path, stringContent)).Result;
        client.Dispose();

        return response;
    }