C# .NET可以';反序列化JSON时不分析嵌套对象
我知道有很多关于这种情况的帖子,但是我找到的所有答案都不适合我,我觉得我的情况有点不同 我有一个名为PropertyValue的类,它是一个描述属性值的元数据类,然后还有一个包含实际值的属性:C# .NET可以';反序列化JSON时不分析嵌套对象,c#,json,C#,Json,我知道有很多关于这种情况的帖子,但是我找到的所有答案都不适合我,我觉得我的情况有点不同 我有一个名为PropertyValue的类,它是一个描述属性值的元数据类,然后还有一个包含实际值的属性: public sealed class PropertyValue { public PropertyValue() { } public string PropertyName { get; set; } public string Cate
public sealed class PropertyValue
{
public PropertyValue()
{
}
public string PropertyName { get; set; }
public string CategoryName { get; }
public string DisplayName { get; }
public int PropertyId { get; }
public string TypeName { get; set;}
public string ToolTip { get; set;}
public string Description { get; }
public object CurrentValue { get; set; }
}
TypeName属性实际上说明了对象CurrentValue的类型,值的范围从System.Int32到我们公司构建的专有对象。问题是,当我尝试使用JsonConvert.DeserializeObject(属性)时,它会反序列化除CurrentValue属性之外的所有内容。我尝试在构造函数中为我们处理的所有类型使用switch语句,并创建该类的新实例,但它没有解析JSON中的嵌套值
有什么想法吗
编辑:我的JSON显示了我们的一个时区类:
{
"PropertyName":"TimeZone",
"CategoryName":"TBD",
"DisplayName":"TimeZone",
"PropertyId":15,
"TypeName":"Namespace.TimeZoneReference",
"ToolTip":"",
"Description":"",
"CurrentValue":{
"timeZoneID":21,
"timeZoneName":"Eastern Standard Time"
}
}
如果您得到的是
null
CurrentValue,那么我将检查在反序列化过程中是否抛出任何错误。如果CurrentValue确实有一个值(我怀疑可能是一个字符串化的对象?),那么您需要编写一个定制来获得您想要的对象。听起来您好像在试图重新发明Json.NET。由于您不使用此设置,而是自己序列化CurrentValue
的类型名称,因此需要创建一个来填充PropertyValue
并将CurrentValue
反序列化为所需的类型。否则,Json.NET将把当前值反序列化为原语(如long
或string
)或对象(如非原语Json值)。(后者是在注释中提到的两个或三个键/值对周围用花括号括起来的字符串值。)
以下是适用于您的类型的一种可能的转换器:
[JsonConverter(typeof(PropertyValueConverter))]
public sealed class PropertyValue
{
public PropertyValue(object CurrentValue)
{
SetCurrentValue(CurrentValue);
}
public PropertyValue()
{
}
public string PropertyName { get; set; }
public string CategoryName { get; set; }
public string DisplayName { get; set; }
public int PropertyId { get; set; }
public string TypeName { get; set; }
public string ToolTip { get; set; }
public string Description { get; set; }
public object CurrentValue { get; set; }
public void SetCurrentValue(object value)
{
CurrentValue = value;
if (value == null)
TypeName = null;
else
TypeName = value.GetType().AssemblyQualifiedName;
}
}
public class PropertyValueConverter : JsonConverter
{
public override bool CanConvert(Type objectType)
{
return typeof(PropertyValue).IsAssignableFrom(objectType);
}
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{
if (reader.TokenType == JsonToken.Null)
return null;
var propertyValue = (existingValue as PropertyValue ?? new PropertyValue());
var obj = JObject.Load(reader);
// Remove the CurrentValue property for manual deserialization, and deserialize
var jValue = obj.GetValue("CurrentValue", StringComparison.OrdinalIgnoreCase).RemoveFromLowestPossibleParent();
// Load the remainder of the properties
serializer.Populate(obj.CreateReader(), propertyValue);
// Convert the type name to a type.
// Use the serialization binder to sanitize the input type! See
// https://stackoverflow.com/questions/39565954/typenamehandling-caution-in-newtonsoft-json
if (!string.IsNullOrEmpty(propertyValue.TypeName) && jValue != null)
{
string typeName, assemblyName;
ReflectionUtils.SplitFullyQualifiedTypeName(propertyValue.TypeName, out typeName, out assemblyName);
var type = serializer.Binder.BindToType(assemblyName, typeName);
if (type != null)
propertyValue.SetCurrentValue(jValue.ToObject(type, serializer));
}
return propertyValue;
}
public override bool CanWrite { get { return false; } }
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
{
throw new NotImplementedException();
}
}
public static class JsonExtensions
{
public static JToken RemoveFromLowestPossibleParent(this JToken node)
{
if (node == null)
return null;
var contained = node.AncestorsAndSelf().Where(t => t.Parent is JContainer && t.Parent.Type != JTokenType.Property).FirstOrDefault();
if (contained != null)
contained.Remove();
// Also detach the node from its immediate containing property -- Remove() does not do this even though it seems like it should
if (node.Parent is JProperty)
((JProperty)node.Parent).Value = null;
return node;
}
}
public static class ReflectionUtils
{
// Utilities taken from https://github.com/JamesNK/Newtonsoft.Json/blob/master/Src/Newtonsoft.Json/Utilities/ReflectionUtils.cs
// I couldn't find a way to access these directly.
public static void SplitFullyQualifiedTypeName(string fullyQualifiedTypeName, out string typeName, out string assemblyName)
{
int? assemblyDelimiterIndex = GetAssemblyDelimiterIndex(fullyQualifiedTypeName);
if (assemblyDelimiterIndex != null)
{
typeName = fullyQualifiedTypeName.Substring(0, assemblyDelimiterIndex.GetValueOrDefault()).Trim();
assemblyName = fullyQualifiedTypeName.Substring(assemblyDelimiterIndex.GetValueOrDefault() + 1, fullyQualifiedTypeName.Length - assemblyDelimiterIndex.GetValueOrDefault() - 1).Trim();
}
else
{
typeName = fullyQualifiedTypeName;
assemblyName = null;
}
}
private static int? GetAssemblyDelimiterIndex(string fullyQualifiedTypeName)
{
int scope = 0;
for (int i = 0; i < fullyQualifiedTypeName.Length; i++)
{
char current = fullyQualifiedTypeName[i];
switch (current)
{
case '[':
scope++;
break;
case ']':
scope--;
break;
case ',':
if (scope == 0)
{
return i;
}
break;
}
}
return null;
}
}
完成此操作后,Json.NET将输出一个“$type”
属性,指示CurrentObject
的实际类型,并在反序列化过程中自动使用该类型,例如:
{
"CurrentValue": {
"$type": "Question42537050.ExampleClass1, Tile",
"Foo": "hello"
},
"PropertyName": "name1",
"CategoryName": null,
"DisplayName": null,
"PropertyId": 0,
"TypeName": "Question42537050.ExampleClass1, Tile, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null",
"ToolTip": "tip1",
"Description": null
}
当然,如果这样做,类型名称将在JSON中出现两次—一次用于TypeName
属性,一次用于JSON.NET的$type
属性。此设置仅适用于复杂对象和数组,而不适用于基本类型
在这两种情况下,出于安全原因,您应该在创建类型实例之前清理
TypeName
,原因如下。“我的代码”假设您已设置为使用,但您可以在PropertyValueConverter.ReadJson()
本身中实现一些验证逻辑。是调试器中的CurrentValue为null还是引发错误?它实际上在json字符串中显示一个读取的值,但在反序列化之后,它只是显示为一个字符串值,两个或三个键/值对之间用花括号括起来。你能分享你的JSON吗?@Coder-我在帖子中添加了我的JSON。这里发布的答案中有没有得到你期望的结果?谢谢!我不得不做一些修改,因为专有的东西,但这是完美的工作!
{
"CurrentValue": {
"$type": "Question42537050.ExampleClass1, Tile",
"Foo": "hello"
},
"PropertyName": "name1",
"CategoryName": null,
"DisplayName": null,
"PropertyId": 0,
"TypeName": "Question42537050.ExampleClass1, Tile, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null",
"ToolTip": "tip1",
"Description": null
}