反序列化$ ref和$ id [英] Deserializing $ref and $id
问题描述
因此,我试图反序列化具有以下属性的对象:$ ref和$ id.我尝试在Dictionary和通过JsonPropertyAttribute指定namingconventions的对象之间进行切换. 序列化有效,但是反序列化无效.我不断收到的错误是:
So I'm trying to deserialize an object that has properties: $ref and $id. I have tried going between Dictionary as well as an object where I have specified namingconventions via JsonPropertyAttribute. Serialization works, but deserialization doesn't. The error I keep getting is:
在JSON字符串中找到其他文本 完成反序列化对象后.
Additional text found in JSON string after finishing deserializing object.
所有三个样本均失败的样本代码.
Sample code where all three samples, fail.
[Serializable]
public class Ref
{
[JsonProperty(PropertyName = "$ref")]
public virtual string RefName { get; set; }
[JsonProperty(PropertyName = "$id")]
public virtual int Id { get; set; }
}
[Serializable]
public class Child
{
public virtual string Name { get; set; }
[JsonProperty(IsReference = true)]
public virtual Ref Father { get; set; }
}
class Program
{
static void Main(string[] args)
{
//Additional text found in JSON string after finishing deserializing object.
//Test 1
var reference = new Dictionary<string, object>();
reference.Add("$ref", "Persons");
reference.Add("$id", 1);
var child = new Dictionary<string, object>();
child.Add("_id", 2);
child.Add("Name", "Isabell");
child.Add("Father", reference);
var json = JsonConvert.SerializeObject(child);
var obj = JsonConvert.DeserializeObject<Dictionary<string, object>>(json); //Exception
//Test 2
var refOrg = new Ref {RefName = "Parents", Id = 1};
var refSer = JsonConvert.SerializeObject(refOrg);
var refDeser = JsonConvert.DeserializeObject<Ref>(refSer); //Exception
//Test 3
var childOrg = new Child {Father = refOrg, Name = "Isabell"};
var childSer = JsonConvert.SerializeObject(childOrg);
var childDeser = JsonConvert.DeserializeObject<Child>(refSer); //Exception
}
}
推荐答案
在尝试反序列化swagger/json模式文档时,我遇到了相同的问题.解决方案是:
I have the same issue when trying to deserialize a swagger/json schema document. The solution is:
JsonSerializerSettings settings = new JsonSerializerSettings();
settings.MetadataPropertyHandling = MetadataPropertyHandling.Ignore;
这篇关于反序列化$ ref和$ id的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!