这是我的代码:
Encoding enc = System.Text.Encoding.GetEncoding(1252);
StreamReader loResponseStream = new StreamReader(resp.GetResponseStream(), enc);
JsonSerializer serializer = new JsonSerializer();
JsonTextReader jsreader = new JsonTextReader(loResponseStream);
results = (mHealthData)serializer.Deserialize(jsreader, typeof(mHealthData)); ***
loResponseStream.Close();
public class mHealthData
{ // Class for the Mhealth Data
public class RootObject
{
public string source { get; set; }
public string name { get; set; }
public string type { get; set; }
public string unit { get; set; }
public double value { get; set; }
public string timestamp { get; set; }
}
}
这是我在标有 ** 的行上收到的错误:
Cannot deserialize the current JSON array (e.g. [1,2,3]) into type 'MHealthPlugin.mHealthData' because the type requires a JSON object (e.g. {"name":"value"}) to deserialize correctly. To fix this error either change the JSON to a JSON object (e.g. {"name":"value"}) or change the deserialized type to an array or a type that implements a collection interface (e.g. ICollection, IList) like
List<T>
that can be deserialized from a JSON array. JsonArrayAttribute can also be added to the type to force it to deserialize from a JSON array.
我不知道如何解决这个问题。我试过输入 List<mHealthData>
代码中几乎无处不在,但无济于事。其他其余的电话我都可以正常工作。
作为引用,下面是我尝试解析的 JSON 的示例:
[{"source":"hi","name":"G","type":"number","unit":null,"value":126,"timestamp":"1974-07-27T09:35:12Z"},{"source":"hi","name":"G","type":"number","unit":null,"value":120,"timestamp":"1974-07-27T09:35:12Z"}]
最佳答案
您的 mHealthData
类中没有任何内容,除了一个嵌套类。退后一步,看看您的数据应该如何定义。
看起来您需要一个 RootObject
类。在这种情况下,类应该是:
public class RootObject
{
public string source { get; set; }
public string name { get; set; }
public string type { get; set; }
public string unit { get; set; }
public double value { get; set; }
public string timestamp { get; set; }
}
然后当您反序列化时,您最终会得到一个 RootObject[]
类型的对象 - 您的 JSON 只是一个数组,而不是包含数组的对象。
关于c# - 将 Json 数组解析为 C# 类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17095690/