- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我遇到的问题是如何反序列化以下 JSON。 Answer 的值有时为 NULL、true、整数、 bool 值或包含另一个 JSON 列表(id、描述等)。
我做的第一步是在 Visual Studio 中复制并粘贴 special as class。这为我提供了以下问题类。
然后我尝试反序列化它(遵循 C# - rawResponse 是 JSON)。但是,我得到“Newtonsoft.Json.JsonSerializationException:'无法将当前 JSON 数组(例如 [1,2,3])反序列化为类型 Applicated.Questions,因为该类型需要 JSON 对象(例如 {"name":"value "}) 正确反序列化....“
我知道这与映射不正确有关。
因此,尝试通过将响应保存在动态变量中来将所有这些都放在 foreach 循环中(请注意,我确实为此从 Questions 类中删除了 Property1)。但是,Answer 中的某些结果会将字符串 Id、Description 等存储在 Answer 字段中。有没有更简单的方法,我好像遇到了心理障碍?
JSON:
[
{
"Answer": true,
"QuestionId": 55,
"Title": "Are you Married?",
"AnswerType": "Boolean"
},
{
"Answer": {
"Id": "1",
"Description": "Female",
"Reference": "F",
"ArchiveDate": null,
"ParentId": null,
"OptionType": {
"Id": 40,
"Type": "dropdown"
}
},
"QuestionId": 778,
"Title": "Gender",
"AnswerType": "Option”
}
]
类:
public class Questions
{
public Class1[] Property1 { get; set; }
}
public class Class1
{
public object Answer { get; set; }
public int QuestionId { get; set; }
public string Title { get; set; }
public string AnswerType { get; set; }
}
C#:
Questions result = JsonConvert.DeserializeObject<Questions>(rawResponse);
C# 动态 Foreach
dynamic result = JsonConvert.DeserializeObject(rawResponse);
var lstQuestionObjects = new List<Questions>();
foreach(var obj in result)
{
lstQuestionObjects.Add(new Questions()
{
Answer = (obj.Answer !=null) ? obj.Answer.ToString() :"",
QuestionId = int.Parse(obj.QuestionId.ToString()),
Title = (obj.Title != null) ? obj.Title.ToString() : "",
AnswerType = (obj.AnswerType != null) ? obj.AnswerType.ToString() : ""
});
}
最佳答案
这取决于您需要什么级别的互操作性,但首先要认识到的是,在 JSON.Net 中,JSON 文件中的所有 tokens 在内部都继承自 JToken,而不是使用无类型的 < em>object 在您的模型中引用,您将通过将 dynamic 属性键入为 JToken
来获得更好的默认反序列化支持。
这个简单的解决方案在 Question
类上显示了一个帮助方法,该方法将 Answer 解析为强类型对象引用。根据您的实现要求,您甚至可能不需要对答案的强类型访问,但是此方法允许您在反序列化完成后对记录值进行后处理和故障排除。
https://dotnetfiddle.net/FwFyOU
List<Question> questions = JsonConvert.DeserializeObject<List<Question>>(GetJSON());
FiddleHelper.WriteTable(questions);
foreach(var question in questions)
{
object answer = question.GetTypedAnswer();
Console.WriteLine("Question: [{0}] {1}: ({2}) {3}", question.QuestionId, question.Title, answer.GetType().Name, answer );
}
注意:根本不需要定义一个名为Questions
的类。
public class Question
{
public JToken Answer { get; set; }
public int QuestionId { get; set; }
public string Title { get; set; }
public string AnswerType { get; set; }
public object GetTypedAnswer ()
{
switch(AnswerType.ToLower())
{
case "boolean":
return Answer.Value<bool>();
case "string":
return Answer.Value<string>();
case "option":
return (Answer as JObject).ToObject<Option>();
default:
return Answer;
}
}
}
public class Option
{
public string Id { get; set; }
public string Description { get; set; }
public string Reference { get; set; }
public DateTime? ArchiveDate { get; set; }
public string ParentId { get; set; }
public OptionType OptionType { get;set; }
public override string ToString()
{
return String.Format("[{0}] {1} ({2})", Reference, Description, OptionType.Type);
}
}
public class OptionType
{
public int Id { get; set; }
public string Type { get; set; }
}
回答 | 问题编号 | 标题 | 答案类型 |
---|---|---|---|
是的 | 55 | 你结婚了吗? | bool 值 |
{ "Id": "1", "Description": "Female", "Reference": "F", "ArchiveDate": null, "ParentId": null, "OptionType": { "Id": 40 , "类型": "下拉菜单"} } | 778 | 性别 | 选项 |
Question: [55] Are you Married?: (Boolean) True
Question: [56] What is your name?: (String) Mr John Doe
Question: [778] Gender: (Option) [F] Female (dropdown)
另一种解决方案是使用 JsonConverter对于 Answer
属性,但是在这种情况下,解析类型所需的元数据是在父 token 中定义的,而不是在值本身中,这意味着您的自定义转换器将需要通过试用来解析类型如果要比较的类型很多,错误可能会非常慢。
折衷方案是为 Question
类本身使用自定义转换器,选择一种方法而不是另一种方法取决于您的需求以及需要解析多少类型(如果需要解析)完全没有。
https://dotnetfiddle.net/m46NaX
List<Question> questions = JsonConvert.DeserializeObject<List<Question>>(GetJSON());
FiddleHelper.WriteTable(questions);
foreach(var question in questions)
{
Console.WriteLine("Question: [{0}] {1}: ({2}) {3}", question.QuestionId, question.Title, question.Answer.GetType().Name, question.Answer );
}
[JsonConverter(typeof(QuestionConverter))]
public class Question
{
public object Answer { get; set; }
public int QuestionId { get; set; }
public string Title { get; set; }
public string AnswerType { get; set; }
}
public class QuestionConverter : JsonConverter<Question>
{
public override Question ReadJson(JsonReader reader, Type objectType, Question existingValue, bool hasExistingValue, JsonSerializer serializer)
{
JObject item = JObject.Load(reader);
var result = new Question();
result.QuestionId = item.GetValue(nameof(result.QuestionId)).Value<int>();
result.Title = item.GetValue(nameof(result.Title)).Value<string>();
result.AnswerType = item.GetValue(nameof(result.AnswerType)).Value<string>();
var answer = item.GetValue(nameof(result.Answer));
switch(result.AnswerType.ToLower())
{
case "boolean":
result.Answer = answer.Value<bool>();
break;
case "string":
result.Answer = answer.Value<string>();
break;
case "option":
result.Answer = (answer as JObject).ToObject<Option>();
break;
default:
result.Answer = answer;
break;
}
return result;
}
public override bool CanWrite{ get => false; }
public override void WriteJson(JsonWriter writer, Question value, JsonSerializer serializer) { }
}
public class Option
{
public string Id { get; set; }
public string Description { get; set; }
public string Reference { get; set; }
public DateTime? ArchiveDate { get; set; }
public string ParentId { get; set; }
public OptionType OptionType { get;set; }
public override string ToString()
{
return String.Format("[{0}] {1} ({2})", Reference, Description, OptionType.Type);
}
}
public class OptionType
{
public int Id { get; set; }
public string Type { get; set; }
}
关于c# - 反序列化动态 JSON,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68226154/
我目前正在对一个 mmorpg 的二进制网络协议(protocol)进行逆向工程。我正在用 java 实现该协议(protocol)。 对于每个数据包类型,我将创建一个表示二进制数据的类。 例如,聊天
我正在尝试围绕现有类编写半透明包装器,我希望它能够模仿其他类的序列化。 例如,给定以下类: class Foo { [JsonConverter(CustomConverter)] s
是否有使用 Jackson 序列化和反序列化枚举集的简单方法? private enum Type { YES, NO } @JacksonXmlProperty(localName = "t
我很想知道当我们反序列化一个对象时会发生什么。 例如,如果我的类对象由许多其他对象组成,对象创建过程如何在反序列化过程中发生 最佳答案 对象是用默认的初始化字段创建的,然后用从串行流中获取的属性值填充
我正在尝试序列化和反序列化(使用 QDataStream 但这与这里无关)一个 enum class变量: enum class Type : char { Trivial, Comp
我不确定这到底有什么问题...它不会为我编译,我将它从 c 翻译成 C++(或尝试)...是的,我是初学者。谢谢! #include #include using namespace std; i
我遇到的问题与此处描述的问题非常相似:Combining type and field serializers case class(id: Option[UUID], otherValue:Stri
我们知道base中的apply()可以对数组的边距应用一个函数,边距应该是行或列。我想将边距扩大到“对角线” 和“反对角线”。结构看起来像 diagApply <- function(x, FUN,
我找到了 JSON serialization and deserialization to objects in Flutter 的例子但是如何使用像这样的人员列表来做到这一点: [ {
我有一个相当大的terms聚合结果,这些结果被加载到下拉列表中以提供filter功能。 可以说,我的下拉列表中有4000多种动物。我的另一个下拉列表有4种动物颜色。 例, animal --> ["d
我需要将 C# (.NET Framework 4.5.2) 中的一个类与 XML 序列化(反序列化),该类具有 string 的字典属性。键和 string[]数组值。我正在使用 Serializa
[已解决]应用给定的解决方案,效果很好! 程序的目的:在用户打开和关闭程序时保存/重新加载以前的数据。 我曾经用一个对象(obj)成功(反)序列化,现在我有两个不同类的不同对象。 我试图通过查看其他帖
问题 假设我有一个代表某事或其他的枚举: public enum ResultState { Found, Deleted, NotFound } 在我的序列化 json 中,
是否有取消 JSON 字符串的功能?我猜它不会内置到 JQuery 中,但它可以通过编写一个操纵字符串的脚本来实现吗?我在下面遇到了这个问题。 我正在使用 NYTimes API,但它不支持 JSON
对于这个问题,假设当对象完全写入流并成功读出时,或者当对象部分写入流并且读回对象时发生异常时,序列化/反序列化是原子的。假设写操作可能无法成功完成,例如因为停电了。 在Serializable的描述中
有谁知道时序检查是否仍在检测虚拟环境?我尝试使用 rdtsc 指令来获取 cpu 周期并比较真实 linux 机器和在 virtualbox 上运行的 linux 之间的结果。但结果似乎不稳定。有时,
我正在对一个(外部给定的)XML 文件进行操作,该文件具有以下形式的元素 10 20 30 40 50 60 70 80 我知道如何将属性作为属性处理(通过使用 [XmlAttri
我有一个通用的序列化器和反序列化器,用于通过网络连接发送的消息: public static async Task SerializeObject(Object obj) {
我正在考虑将当前基于 WCF 的应用程序迁移到 protobuf-net.Grpc。这似乎是可行的,但是我无法在不包含所有具有 [ProtoInclude] 属性的派生类的情况下使(DTO 类)基类的
我正在尝试将一些数据保存到文件中,但文件保存到的目录不正确。 using (StreamWriter sw = new StreamWriter(dir + "\\temp" + x + ".txt"
我是一名优秀的程序员,十分优秀!