C#JsonConvert.DeserializeAnonymousType失败

我试图反序列化Azurefunction应用程序中的字符串输入。 我的意见是

[{"messageid":1, "deviceid":"Android", "temperature":20.0, "humidity":47.0, "eventprocessedutctime":"2017-12-01T10:35:57.8331048Z", "result1":{"temperature":"20","humidity":"47","Scored Labels":"NO","Scored Probabilities":"0.450145334005356"}}] 

我尝试使用此代码运行。

 #r "Newtonsoft.Json" using System.Configuration; using System.Text; using System.Net; using Microsoft.Azure.Devices; using Newtonsoft.Json; // create proxy static Microsoft.Azure.Devices.ServiceClient client = ServiceClient.CreateFromConnectionString(ConfigurationManager.AppSettings["myIoTHub"]); public static async Task Run(string input, HttpRequestMessage req, TraceWriter log) { log.Info($"ASA Job: {input}"); var data = JsonConvert.DeserializeAnonymousType(input, new { deviceid = "" }); if (!string.IsNullOrEmpty(data?.deviceid)) { string deviceId = data.deviceid; // string deviceId = data[0].deviceid; log.Info($"Device: {deviceId}"); // cloud-to-device message var msg = JsonConvert.SerializeObject(new { input }); var c2dmsg = new Microsoft.Azure.Devices.Message(Encoding.ASCII.GetBytes(msg)); // send AMQP message await client.SendAsync(deviceId, c2dmsg); } return req.CreateResponse(HttpStatusCode.NoContent); } 

我感兴趣的是deviceid和Scored Labels。 但是现在我甚至无法提取其中一个。 更多的得分标签由空间组成。 result1是Azure机器学习返回的结果,因此似乎无法重命名。

您的问题是您的根JSON容器是一个数组,而不是一个对象:

  • 数组是有序的值集合。 数组以[ (左括号)开头并以]结尾(右括号)。 值以(逗号)分隔。

  • 对象是一组无序的名称/值对。 对象以{ (左括号)开头,以}结尾(右括号)。

正如Json.NET文档中所解释的那样,需要将JSON数组反序列化为集合,例如.Net数组。 这样你就可以做到:

 var dataArray = JsonConvert.DeserializeAnonymousType(input, new [] { new { deviceid = "" } }); var data = dataArray.SingleOrDefault(); 

样品小提琴 。

如果您发现需要从JSON中提取多于一个或两个属性,则可能需要创建要反序列化的显式类型。 为此,您可以使用http://json2csharp.com/或粘贴JSON作为类 。