首页 > 解决方案 > 反序列化 json 格式字符串

问题描述

目前我有一个从服务器接收响应的 websocket 应用程序。

我在用

object obj=new JavaScriptSerializer().Deserialize<CustomerNTF>(e.data);

反序列化 json 字符串。

我应该反序列化的字符串是:

{
  "face_list":[
      {
         "face_detect":{
              "age":65535,
              "beauty":65535,
              "expression":65535,
              "gender":65535,
              "glass":false,
              "smile":65536
           },
           "face_recg":{
           "confidence":82,
           "name":"user",
           "person_id":"person1"
        }
       }
     ],
    "face_num":1,
    "msg_id":"FACE_DETECT"
}

我试过的:

public class CustomerNTF
{
    public face_list face_list { get; set; }
    public int face_num{get;set;}
    public string msg_id{get;set;}
}
public class face_list
{
    public class face_detect
    {
        public int age { get; set; }
        public int beauty { get; set; }
        public int expression { get; set; }
        public int gender { get; set; }
        public bool glass { get; set; }
        public int smile { get; set; }
    }
    public class face_recg
    {
        public int confidence { get; set; }
        public string name { get; set; }
        public string person_id { get; set; }
    }
}

我收到的错误是数组的反序列化不支持 type face_list

标签: c#stringwebsocketdeserialization

解决方案


你的班级结构是错误的。json 字符串包含一个face_list非单个对象的列表。此外,您当前的face_list类不包含任何属性,只有两个不包含任何值的嵌套类定义。

正确的结构:

public class FaceDetect
{
    public int age { get; set; }
    public int beauty { get; set; }
    public int expression { get; set; }
    public int gender { get; set; }
    public bool glass { get; set; }
    public int smile { get; set; }
}

public class FaceRecg
{
    public int confidence { get; set; }
    public string name { get; set; }
    public string person_id { get; set; }
}

public class FaceList
{
    public FaceDetect face_detect { get; set; }
    public FaceRecg face_recg { get; set; }
}

public class CustomerNTF
{
    public List<FaceList> face_list { get; set; }
    public int face_num { get; set; }
    public string msg_id { get; set; }
}

将来,如果您不确定您的类结构必须如何匹配给定的 json 字符串,您可以使用json2csharp 之类的工具。这会为您生成正确的结构。


推荐阅读