简体   繁体   English

如何在 C# 中反序列化 json

[英]How can I deserialize a json in c#

Hello I'm trying to deserialize the following json in c#:您好,我正在尝试在 c# 中反序列化以下 json:

{  
 "Labels":[  
    {  
       "DeviceID":9,
       "Disabled":false,
       "Id":0,
       "Internal":"1@CB_I_AllCloseCheck",
       "Label":"CB_I_AllCloseCheck",
       "MAddress":0,
       "Mask":2147483648,
       "ModuleID":4,
       "Offset":0,
       "Position":1,
       "SectionID":0,
       "Type":16
     }
   ]
 }

With the following code line:使用以下代码行:

Labels myDeserializedObjList = (Labels)JsonConvert.DeserializeObject(sub, typeof(Labels));

The string sub contains this json like a string.字符串 sub 像字符串一样包含这个 json。 Where my class Labels is the following:我的班级标签如下:

public class Labels
    {
        public string DeviceID { get; set; }
        public string Disabled { get; set; }
        public string IValue { get; set; }
        public string Id { get; set; }
        public string Internal { get; set; }
        public string Label { get; set; }
        public string MAddress { get; set; }
        public string Mask { get; set; }
        public string ModuleID { get; set; }
        public string Offset { get; set; }
        public string Position { get; set; }
        public string SectionID { get; set; }
        public string Type { get; set; }
    }

But the result of this operation is all my atributes equal to null.但是这个操作的结果是我所有的属性都等于null。 Anyone knows what I'm doing wrong?有谁知道我做错了什么?

At the moment your root object is just that: an object.目前你的根对象就是:一个对象。 It's not an array.它不是一个数组。 Its only property (Labels) is an array.它唯一的属性(标签)是一个数组。

You should add an extra "root object" class:您应该添加一个额外的“根对象”类:

public class LabelsContainer
{
    public IList<Labels> Labels {get;set;}
}

And then deserialize to that:然后反序列化为:

var labelsContainer = Newtonsoft.Json.JsonConvert.DeserializeObject<LabelsContainer>(data);
var labels = labelsContainer?.Labels;

The JSON string shows an object with a Labels property that contains an array of labels. JSON 字符串显示具有 Labels 属性的对象,该对象包含标签数组。 You need to try something like :你需要尝试类似的东西:

class LabelsDTO
{
    public Labels[] Labels{get;set;}
}

...

var dto = JsonConvert.DeserializeObject<LabelsDTO>(sub);

for (var label in dto.Labels)
{
...
}

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

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