使用HTTPClient的PostAsync方法发送数组

5

我有一组位置点的数组(纬度、经度和创建时间),需要批量发送。然而,当我使用 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 数据的方法?


首先,服务器期望什么? - Nkosi
@Nkosi,我已经为您更新了帖子。 - Edie W.
@dbc 你怎样使用 PostAsync 并发送对象?我已经包含了我的 Location.cs。 - Edie W.
1个回答

6
构建模型,然后在发布之前将整个模型序列化。
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);

谢谢!我从服务器响应中得到了401错误,但我肯定是自己的问题! - Edie W.

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接