使用 JSON.NET(很棒的库!)解决了这个问题。现在,首先,对象被序列化并准确引用到我想要它们的位置;其次,没有大量的“$id”和“$ref”字段。在我的解决方案中,对象的第一个属性用作其标识符。
我创建了两个JsonConvertor
s(用于引用对象和引用对象):
interface IJsonLinkable
{
string Id { get; }
}
class JsonRefConverter : JsonConverter
{
public override void WriteJson (JsonWriter writer, object value, JsonSerializer serializer)
{
writer.WriteValue(((IJsonLinkable)value).Id);
}
public override object ReadJson (JsonReader reader, Type type, object existingValue, JsonSerializer serializer)
{
if (reader.TokenType != JsonToken.String)
throw new Exception("Ref value must be a string.");
return JsonLinkedContext.GetLinkedValue(serializer, type, reader.Value.ToString());
}
public override bool CanConvert (Type type)
{
return type.IsAssignableFrom(typeof(IJsonLinkable));
}
}
class JsonRefedConverter : JsonConverter
{
public override void WriteJson (JsonWriter writer, object value, JsonSerializer serializer)
{
serializer.Serialize(writer, value);
}
public override object ReadJson (JsonReader reader, Type type, object existingValue, JsonSerializer serializer)
{
var jo = JObject.Load(reader);
var value = JsonLinkedContext.GetLinkedValue(serializer, type, (string)jo.PropertyValues().First());
serializer.Populate(jo.CreateReader(), value);
return value;
}
public override bool CanConvert (Type type)
{
return type.IsAssignableFrom(typeof(IJsonLinkable));
}
}
以及保存引用数据的上下文(每种类型都有一个字典,因此 ID 只需要在相同类型的对象中是唯一的):
class JsonLinkedContext
{
private readonly IDictionary<Type, IDictionary<string, object>> links = new Dictionary<Type, IDictionary<string, object>>();
public static object GetLinkedValue (JsonSerializer serializer, Type type, string reference)
{
var context = (JsonLinkedContext)serializer.Context.Context;
IDictionary<string, object> links;
if (!context.links.TryGetValue(type, out links))
context.links[type] = links = new Dictionary<string, object>();
object value;
if (!links.TryGetValue(reference, out value))
links[reference] = value = FormatterServices.GetUninitializedObject(type);
return value;
}
}
属性上的一些属性是必需的:
[JsonObject(MemberSerialization.OptIn)]
class Family
{
[JsonProperty(ItemConverterType = typeof(JsonRefedConverter))]
public List<Person> persons;
}
[JsonObject(MemberSerialization.OptIn)]
class Person : IJsonLinkable
{
[JsonProperty]
public string name;
[JsonProperty]
public Pos pos;
[JsonProperty, JsonConverter(typeof(JsonRefConverter))]
public Person mate;
[JsonProperty(ItemConverterType = typeof(JsonRefConverter))]
public List<Person> children;
string IJsonLinkable.Id { get { return name; } }
}
[JsonObject(MemberSerialization.OptIn)]
class Pos
{
[JsonProperty]
public int x;
[JsonProperty]
public int y;
}
因此,当我使用此代码进行序列化和反序列化时:
JsonConvert.SerializeObject(family, Formatting.Indented, new JsonSerializerSettings {
NullValueHandling = NullValueHandling.Ignore,
Context = new StreamingContext(StreamingContextStates.All, new JsonLinkedContext()),
});
JsonConvert.DeserializeObject<Family>(File.ReadAllText(@"..\..\Data\Family.json"), new JsonSerializerSettings {
Context = new StreamingContext(StreamingContextStates.All, new JsonLinkedContext()),
});
我得到了这个整洁的 JSON:
{
"persons": [
{
"name": "mom",
"pos": {
"x": 3,
"y": 7
},
"mate": "dad",
"children": [
"bro",
"sis"
]
},
{
"name": "dad",
"pos": {
"x": 4,
"y": 8
},
"mate": "mom",
"children": [
"bro",
"sis"
]
},
{
"name": "bro",
"pos": {
"x": 1,
"y": 5
}
},
{
"name": "sis",
"pos": {
"x": 2,
"y": 6
}
}
]
}
我在我的解决方案中不喜欢的是,我必须使用JObject
,即使从技术上讲它是不必要的。它可能会创建相当多的对象,因此加载会更慢。但看起来这是自定义对象转换器最广泛使用的方法。无论如何,可以用来避免这种情况的方法都是私有的。