Post 使用 C# WebClient 多个 Json 对象

Post With C# WebClient Multiple Json Object

我想发送 Post 带有此 Json 架构的 C# WebClient 请求:

 [
  {
    "id": "00000000-0000-0000-0000-000000000000",
    "points": [
      {
        "timestamp": "2017-12-04T16:07:44.562Z",
        "value": 0
      }
    ]
  }
]

我试过这个:

public class RequestData
{
    public string id {get; set; }
    public points points { get; set; }
}

public class points
{
     public DateTime timestamp { get; set; }
     public float value { get; set; }
}

我的程序:

Random number = new Random();
var req = new RequestData();
req.id = "0e13d9c-571c-44f4-b796-7c40c0e20a1d";
req.points = new points { timestamp = DateTime.UtcNow, value = 
number.Next(100, 99999) };

JsonSerializerSettings settings = new JsonSerializerSettings();
var data = JsonConvert.SerializeObject(req);

WebClient client = new WebClient(); 

client.Headers.Add(HttpRequestHeader.Authorization, 
AquaAtuhorization.accessToken);

client.Headers.Add(HttpRequestHeader.ContentType, "application/json"); 
client.UploadString ("http://localhost:8080/api/v1/data/writeNumericValues",  
data  ); 

而且我总是收到 Http 415(不支持的媒体类型)。

如何将我的 C# 对象格式化为 restApi 接受的格式。

你的Jsonclass需要这样,看http://json2csharp.com/ or use paste as JSON from VS https://blog.codeinside.eu/2014/09/08/Visual-Studio-2013-Paste-Special-JSON-And-Xml/

public class Point
{
  public DateTime timestamp { get; set; }
  public int value { get; set; }
}

public class RootObject
{
  public string id { get; set; }
  public List<Point> points { get; set; }
}`

看JSON,方括号[ ]表示something是一个数组。在这种情况下,RequestDatapoints 都必须是一个数组,请参见下面的示例:

public class RequestData
{
    public string id { get; set; }
    public List<points> points { get; set; }  // I use list, could be an array
}

public class points
{
    public DateTime timestamp { get; set; }
    public float value { get; set; }
}

然后像这样构造您的 req 对象:

var req = new List<RequestData> // Again I use list, could be an array
{
    new RequestData
    {
        id = "0e740d9c-571c-44f4-b796-7c40c0e20a1d",
        points = new List<points> // Defined as a list, even though it has one entry
        {
            new points
            {
                timestamp = DateTime.UtcNow,
                value = number.Next(100, 99999)
            }
        }
    }
};

然后正常序列化,结果如下:

[
  {
    "id":"0e740d9c-571c-44f4-b796-7c40c0e20a1d",
    "points":[
      {
        "timestamp":"2017-12-04T17:12:25.8957648Z",
        "value":59522.0
      }
    ]
  }
]