c# - 反序列化 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
。
解决方案
你的班级结构是错误的。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 之类的工具。这会为您生成正确的结构。
推荐阅读
- php - 如果 Elasticsearch 仍在运行,请使用 PHP 检查
- node.js - 猫鼬虚拟返回null
- c# - Zenject 中方法绑定的多次调用
- sql - 使用 SQL Server 管理工作室生成自动增量 ID 时出现语法错误
- neural-network - 使用预训练的词嵌入 - 如何为未知/OOV 令牌创建向量?
- javascript - 从 HTML 中获取 json 和 preapre 数组以通过 js 发送
- sql - sql while循环通过检查条件是否包含字符串中的单词
- java - PDFBOX:合并添加未使用的字体,如何删除它
- html - 如何在html中显示pdf
- iis - Change domain name through browser - Windows Authentication - SID History