c# - 将 Json 数组解析为 C# 类

标签 c# json

这是我的代码:

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/

相关文章:

c# - MySql数据库中如何调用多个存储过程

c# - 过分热心的字符串常量

javascript - 如何在javascript中将字符串数据转换为Geojson

json - 如何预加载 JSON 数据以便在 Angularjs 模块准备好时可用

c# - 移至 DateTimePicker 中数据输入的后续日期部分

c# - 您如何使用 Fluent Validation 对列表中的每个字符串进行验证?

c# - ServiceStack.Redis 在缓存中存储空对象

javascript - Ajax 成功函数无法处理返回的 json 数据和状态 200/304

PHP json_encode json_decode UTF-8

c# - 如果解析不好,则解析 JSON 语法