【问题标题】:c# JSON Post Issuec# JSON 发布问题
【发布时间】:2015-09-12 20:16:11
【问题描述】:

我无法解决这个问题。如果我在 HTTP Post 之前使用 NewtonSoft 将对象序列化为 JSON,我会从 REST 服务收到 400。如果我只是将 JSON 作为字符串发布,则在下面的代码中作为“jsonx”它可以工作。但是,如果我比较字符串“json”和“jsonx”,它们是相同的。

public async Task<String> TransferAsync(String fromAddress, Int64 amount, String toAddress, String assetId)
{
    Models.CoinPrism.TransferRequest request = new CoinPrism.TransferRequest()
    {
        fees = 1000,
        from = fromAddress,
    };

    request.to[0] = new CoinPrism.Transfer()
    {
        address = toAddress,
        amount = amount,
        asset_id = assetId
    };

    String json = Newtonsoft.Json.JsonConvert.SerializeObject(request);
    String jsonX = "{  \"fees\": 1000,  \"from\": \"1zLkEoZF7Zdoso57h9si5fKxrKopnGSDn\",  \"to\": [    {      \"address\": \"akSjSW57xhGp86K6JFXXroACfRCw7SPv637\",      \"amount\": \"10\",      \"asset_id\": \"AHthB6AQHaSS9VffkfMqTKTxVV43Dgst36\"    }  ]}";

    Uri baseAddress = new Uri("https://api.coinprism.com/");

    using (var httpClient = new HttpClient { BaseAddress = baseAddress })
    {
        using (var content = new StringContent(jsonX, System.Text.Encoding.Default, "application/json"))
        {
            using (var response = await httpClient.PostAsync("v1/sendasset?format=json", content))
            {
                string responseData = await response.Content.ReadAsStringAsync();
                return responseData;
            }
        }
    }
}

型号

public class TransferRequest
{
    public Int64 fees { get; set; }

    public String from { get; set; }

    public Transfer[] to { get; set; }

    public TransferRequest(Int32 n = 1)
    {
        this.to = new Transfer[n];
    }

    public TransferRequest(Transfer transfer)
    {
        this.to = new Transfer[1];
        this.to[0] = transfer;
    }
}

public class Transfer
{
    public String address { get; set; }

    public Int64 amount { get; set; }

    public String asset_id { get; set; }
}

【问题讨论】:

  • 如果json 等于jsonx 那么你会得到同样的结果。
  • 你试过 fiddler 来查看发送的原始内容吗?
  • 你手动写“jsonx”吗?我认为它不能与“json”相同。例如,金额是 Int64,在 "json" 中你会有 "amount":10 而在 "jsonx" 你有 "amount": "10" 就像它是一个字符串

标签: c# json rest


【解决方案1】:

错误的原因是它们是相同的字符串,但编码不同。

您发送的字符串编码错误。

1- 序列化后,将字符串转换为ANSI编码(例如) 2-using (var content = new StringContent(jsonX, System.Text.Encoding.ANSI, "application/json)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-07-02
    • 1970-01-01
    • 2017-03-30
    • 1970-01-01
    • 2020-01-06
    • 2011-09-11
    • 2011-07-25
    • 1970-01-01
    相关资源
    最近更新 更多