简体   繁体   中英

c# JSON Post Issue

I can't work this one out. If I use NewtonSoft to serialize the object to JSON before a HTTP Post, I receive a 400 from the REST Service. If I just post the JSON as a string, in the below code as "jsonx" it works. However, if I compare the strings "json" and "jsonx" they're the same.

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;
            }
        }
    }
}

Models

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; }
}

The reason of the error is that they are identical strings but with different encoding.

You are sending the wrong encoding for the string.

1- After serializing, convert the string to ANSI encoding (for example) 2- using (var content = new StringContent(jsonX, System.Text.Encoding.ANSI, "application/json)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM