我做了一个指向API的POST请求代码,用于执行自动交换程序。 这是代码:
string webAddr = "https://shapeshift.io/shift";
var httpWebRequest = (HttpWebRequest)WebRequest.Create(webAddr);
httpWebRequest.ContentType = "application/json; charset=utf-8";
httpWebRequest.Method = "POST";
using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream()))
{
string json = "{ \"withdrawal\" : \"***ADDRESS WITH LETTER AND NUMBER***\", \"pair\" : \"eth_xmr\" }";
streamWriter.Write(json);
streamWriter.Flush();
}
var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
{
var responseText = streamReader.ReadToEnd();
Console.WriteLine(responseText);
}
执行代码后,我在控制台中获取此代码
{"orderId":"1f90346c-c6d4-4d89-a24c-78b2bbdb6292","deposit":"0x534aa684274b4711f65b2d0e2e403cb169201255","depositType":"ETH","withdrawal":"***ADDRESS WITH LETTER AND NUMBER***","withdrawalType":"XMR"
现在,我想将我从API获得的存款地址放入字符串变量中。我尝试了一些代码,但我无法使其正常工作。那么如何将这个地址放在一个字符串变量中呢?
答案 0 :(得分:1)
你可以反序列化响应并从那里得到你想要的。为了做到这一点,你可以定义一个类,让它命名为ApiResponse
:
public class ApiResponse
{
[JsonProperty("orderId")]
public string orderId { get; set; }
[JsonProperty("deposit")]
public string deposit { get; set; }
[JsonProperty("depositType")]
public string depositType { get; set; }
[JsonProperty("withdrawal")]
public string withdrawal { get; set; }
[JsonProperty("withdrawalType")]
public string withdrawalType { get; set; }
}
然后
var responseText = streamReader.ReadToEnd();
进行反序列化:
var apiResponse = JsonConvert.DeserializeObject<ApiResponse>(responseText);
我使用过Json.NET库。因此,如果您还没有,那么您应该这样做,或者您可以使用另一个库并相应地更改上述代码。