2using System.Diagnostics;
6internal interface IClassDeserializer : IDeserializer
8 public object DeserializeDocument(
MappingContext context,
string?
id,
string? name, ref Utf8FaunaReader reader);
11internal class ClassDeserializer<T> : BaseDeserializer<T>, IClassDeserializer
13 private static readonly
string _idField =
"id";
14 private static readonly
string _nameField =
"name";
20 Debug.Assert(info.
Type == typeof(T));
24 public object DeserializeDocument(
MappingContext context,
string?
id,
string? name, ref Utf8FaunaReader reader)
26 var instance = CreateInstance();
27 if (
id is not
null) TrySetId(instance,
id);
28 if (name is not
null) TrySetName(instance, name);
29 SetFields(instance, context, ref reader,
TokenType.EndDocument);
35 var endToken = reader.CurrentTokenType
switch
37 TokenType.StartDocument =>
TokenType.EndDocument,
38 TokenType.StartObject =>
TokenType.EndObject,
39 var other =>
throw UnexpectedToken(other),
42 var instance = CreateInstance();
43 SetFields(instance, context, ref reader, endToken);
47 private object CreateInstance() => Activator.CreateInstance(_info.Type)!;
51 while (reader.Read() && reader.CurrentTokenType != endToken)
53 if (reader.CurrentTokenType !=
TokenType.FieldName)
54 throw UnexpectedToken(reader.CurrentTokenType);
56 var fieldName = reader.GetString()!;
59 if (fieldName == _idField && reader.CurrentTokenType ==
TokenType.String)
61 TrySetId(instance, reader.GetString()!);
63 else if (fieldName == _nameField && reader.CurrentTokenType ==
TokenType.String)
65 TrySetName(instance, reader.GetString()!);
67 else if (_info.FieldsByName.TryGetValue(fieldName, out var field))
69 field.Property.SetValue(instance, field.Deserializer.Deserialize(context, ref reader));
78 private void TrySetId(
object instance,
string id)
80 if (_info.FieldsByName.TryGetValue(_idField, out var field))
82 if (field.Type == typeof(
long))
84 field.Property.SetValue(instance,
long.Parse(
id));
86 else if (field.Type == typeof(
string))
88 field.Property.SetValue(instance,
id);
97 private void TrySetName(
object instance,
string name)
99 if (_info.FieldsByName.TryGetValue(_nameField, out var field))
101 if (field.Type == typeof(
string))
103 field.Property.SetValue(instance, name);
112 private SerializationException UnexpectedToken(
TokenType tokenType) =>
113 new SerializationException(
114 $
"Unexpected token while deserializing into class {_info.Type.Name}: {tokenType}");
new T Deserialize(MappingContext context, ref Utf8FaunaReader reader)
TokenType
Enumerates the types of tokens used in Fauna serialization.