简体   繁体   English

使用 C# 进行 JSON 反序列化

[英]JSON deserialization with C#

I am trying to deserialize a JSON file but something is not working.我正在尝试反序列化一个 JSON 文件,但有些东西不起作用。 The object results is null after the execution.执行后对象结果为空。

FilePath = openfiledialog.FileName;
JSONfile = File.ReadAllText(FilePath);

JavaScriptSerializer js = new JavaScriptSerializer();
SearchResults results = js.Deserialize<SearchResults>(JSONfile);

在此处输入图片说明

在此处输入图片说明

"searchResults": [
    {
        "startTime": 1604466366253,
        "parameter": {
            "name": "CntIOParts",
            "value": 0,
            "datatype": "int"
        }
    },
    {
        "startTime": 1604478998001,
        "parameter": {
            "name": "CntIOParts",
            "value": 0,
            "datatype": "int"
        }
    }]

The problem with object result being null is because, Serialize doesn't know which object to map on which one.对象结果为空的问题是因为 Serialize 不知道要映射哪个对象。 What you need to have is, rename your class properties similar to that of in the json that you have.您需要的是,重命名您的class属性,类似于您拥有的json中的class属性。 Moreover, your json is not in a correct format.此外,您的 json 格式不正确。 You should not have the name of the outer-most property ( searchResults ).您不应拥有最外层属性 ( searchResults ) 的名称。 The other issue in your models is, you have a List<Parameter> in your model but in your json, Parameter is not an array, so you should make that accept an object instead of an array.您的模型中的另一个问题是,您的模型中有一个List<Parameter>但在您的 json 中, Parameter不是一个数组,因此您应该让它接受一个对象而不是一个数组。

So, in order to get it correctly parsed, make it look like this:所以,为了正确解析它,让它看起来像这样:

[
    {
        "startTime": 1604466366253,
        "parameter": {
            "name": "CntIOParts",
            "value": 0,
            "datatype": "int"
        }
    },
    {
        "startTime": 1604478998001,
        "parameter": {
            "name": "CntIOParts",
            "value": 0,
            "datatype": "int"
        }
    }
]

And your models should like like this:你的模型应该是这样的:

public partial class SearchResult
{
    public long startTime { get; set; }

    public Parameter parameter { get; set; }
}

public partial class Parameter
{

    public string name { get; set; }

    public long value { get; set; }
    
    public string datatype { get; set; }
}

Plus, instead using JavaScriptSerializer I would recommend using the Newtonsoft.Json library to parse the objects.另外,我建议使用Newtonsoft.Json库来解析对象,而不是使用JavaScriptSerializer

FilePath = openfiledialog.FileName;
JSONfile = File.ReadAllText(FilePath);

var results = JsonConvert.DeserializeObject<List<SearchResult>>(JSONfile);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM