簡體   English   中英

使用HTTPClient PostAsync發送數組

[英]Send array using HTTPClient PostAsync

我有一系列需要批量發送的位置點(緯度,經度和created_at)。 但是,當我使用JsonConvert.SerializeObject()它返回一個無法在服務器端點上解析的字符串。

var location_content = new FormUrlEncodedContent(new[] {
    new KeyValuePair<string, string>("access_token", $"{Settings.AuthToken}"),
    new KeyValuePair<string, string>("coordinates", JsonConvert.SerializeObject(locations))
});

var response = await client.PostAsync(users_url + bulk_locations_url, location_content);

結果如下所示:

{"access_token":"XX","coordinates":"[{\"created_at\":\"2018-03-27T21:36:15.308265\",\"latitude\":XX,\"longitude\":XX},{\"created_at\":\"2018-03-27T22:16:15.894579\",\"latitude\":XX,\"longitude\":XX}]"}

坐標數組作為一個大字符串出現,所以它看起來像:"[{\\"created_at\\":它應該是什么時候:[{"created_at":

所以,服務器期待這樣的事情:

{"access_token":"XX","coordinates":[{\"created_at\":\"2018-03-27T21:36:15.308265\",\"latitude\":XX,\"longitude\":XX},{\"created_at\":\"2018-03-27T22:16:15.894579\",\"latitude\":XX,\"longitude\":XX}]}

Location.cs

public class Location
{
    public DateTime created_at { get; set; }
    public double latitude { get; set; }
    public double longitude { get; set; }

    [PrimaryKey, AutoIncrement, JsonIgnore]
    public int id { get; set; }

    [JsonIgnore]
    public bool uploaded { get; set; }

    public Location()
    {

    }

    public Location(double lat, double lng)
    {
        latitude = lat;
        longitude = lng;

        uploaded = false;
        created_at = DateTime.UtcNow;

        Settings.Latitude = latitude;
        Settings.Longitude = longitude;
    }

    public Location(Position position) : this(position.Latitude, position.Longitude) {}
}

有沒有辦法讓鍵值對成為<string, []> 我還沒有找到一個不使用<string, string>對的例子。

HttpClient是否有針對json數據數組的另一種解決方法?

構建模型,然后在發布之前序列化整個事物

var model = new{
    access_token = Settings.AuthToken,
    coordinates = locations
};
var json = JsonConvert.SerializeObject(model);
var location_content = new StringContent(json, Encoding.UTF8, "application/json");

var response = await client.PostAsync(users_url + bulk_locations_url, location_content);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM