发布C#WebClient多个Json对象

时间:2017-12-04 17:07:03

标签: c# json webclient

我想用这个Json Schema用C#WebClient发送Post Request:

 [
  {
    "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加速格式。

2 个答案:

答案 0 :(得分:1)

查看JSON,方括号[ ]表示某个东西是数组。在这种情况下,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
      }
    ]
  }
]

答案 1 :(得分:0)

您的Json类必须如下所示,请参阅http://json2csharp.com/或使用粘贴作为VS https://blog.codeinside.eu/2014/09/08/Visual-Studio-2013-Paste-Special-JSON-And-Xml/中的JSON

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