-
-
Notifications
You must be signed in to change notification settings - Fork 158
/
Copy pathJsonApiDeSerializer.cs
265 lines (209 loc) · 10 KB
/
JsonApiDeSerializer.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using JsonApiDotNetCore.Extensions;
using JsonApiDotNetCore.Internal;
using JsonApiDotNetCore.Internal.Generics;
using JsonApiDotNetCore.Models;
using JsonApiDotNetCore.Models.Operations;
using JsonApiDotNetCore.Services;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
namespace JsonApiDotNetCore.Serialization
{
public class JsonApiDeSerializer : IJsonApiDeSerializer
{
private readonly IJsonApiContext _jsonApiContext;
[Obsolete(
"The deserializer no longer depends on the IGenericProcessorFactory",
error: false)]
public JsonApiDeSerializer(
IJsonApiContext jsonApiContext,
IGenericProcessorFactory genericProcessorFactory)
{
_jsonApiContext = jsonApiContext;
}
public JsonApiDeSerializer(IJsonApiContext jsonApiContext)
{
_jsonApiContext = jsonApiContext;
}
public object Deserialize(string requestBody)
{
try
{
var bodyJToken = JToken.Parse(requestBody);
if (RequestIsOperation(bodyJToken))
{
_jsonApiContext.IsBulkOperationRequest = true;
// TODO: determine whether or not the token should be re-used rather than performing full
// deserialization again from the string
var operations = JsonConvert.DeserializeObject<OperationsDocument>(requestBody);
if (operations == null)
throw new JsonApiException(400, "Failed to deserialize operations request.");
return operations;
}
var document = bodyJToken.ToObject<Document>();
_jsonApiContext.DocumentMeta = document.Meta;
var entity = DocumentToObject(document.Data);
return entity;
}
catch (Exception e)
{
throw new JsonApiException(400, "Failed to deserialize request body", e);
}
}
private bool RequestIsOperation(JToken bodyJToken)
=> _jsonApiContext.Options.EnableOperations
&& (bodyJToken.SelectToken("operations") != null);
public TEntity Deserialize<TEntity>(string requestBody) => (TEntity)Deserialize(requestBody);
public object DeserializeRelationship(string requestBody)
{
try
{
var data = JToken.Parse(requestBody)["data"];
if (data is JArray)
return data.ToObject<List<DocumentData>>();
return new List<DocumentData> { data.ToObject<DocumentData>() };
}
catch (Exception e)
{
throw new JsonApiException(400, "Failed to deserialize request body", e);
}
}
public List<TEntity> DeserializeList<TEntity>(string requestBody)
{
try
{
var documents = JsonConvert.DeserializeObject<Documents>(requestBody);
var deserializedList = new List<TEntity>();
foreach (var data in documents.Data)
{
var entity = DocumentToObject(data);
deserializedList.Add((TEntity)entity);
}
return deserializedList;
}
catch (Exception e)
{
throw new JsonApiException(400, "Failed to deserialize request body", e);
}
}
public object DocumentToObject(DocumentData data)
{
if (data == null) throw new JsonApiException(422, "Failed to deserialize document as json:api.");
var contextEntity = _jsonApiContext.ContextGraph.GetContextEntity(data.Type?.ToString());
_jsonApiContext.RequestEntity = contextEntity;
var entity = Activator.CreateInstance(contextEntity.EntityType);
entity = SetEntityAttributes(entity, contextEntity, data.Attributes);
entity = SetRelationships(entity, contextEntity, data.Relationships);
var identifiableEntity = (IIdentifiable)entity;
if (data.Id != null)
identifiableEntity.StringId = data.Id?.ToString();
return identifiableEntity;
}
private object SetEntityAttributes(
object entity, ContextEntity contextEntity, Dictionary<string, object> attributeValues)
{
if (attributeValues == null || attributeValues.Count == 0)
return entity;
var entityProperties = entity.GetType().GetProperties();
foreach (var attr in contextEntity.Attributes)
{
var entityProperty = entityProperties.FirstOrDefault(p => p.Name == attr.InternalAttributeName);
if (entityProperty == null)
throw new ArgumentException($"{contextEntity.EntityType.Name} does not contain an attribute named {attr.InternalAttributeName}", nameof(entity));
if (attributeValues.TryGetValue(attr.PublicAttributeName, out object newValue))
{
var convertedValue = ConvertAttrValue(newValue, entityProperty.PropertyType);
entityProperty.SetValue(entity, convertedValue);
if (attr.IsImmutable == false)
_jsonApiContext.AttributesToUpdate[attr] = convertedValue;
}
}
return entity;
}
private object ConvertAttrValue(object newValue, Type targetType)
{
if (newValue is JContainer jObject)
return DeserializeComplexType(jObject, targetType);
var convertedValue = TypeHelper.ConvertType(newValue, targetType);
return convertedValue;
}
private object DeserializeComplexType(JContainer obj, Type targetType)
{
return obj.ToObject(targetType, JsonSerializer.Create(_jsonApiContext.Options.SerializerSettings));
}
private object SetRelationships(
object entity,
ContextEntity contextEntity,
Dictionary<string, RelationshipData> relationships)
{
if (relationships == null || relationships.Count == 0)
return entity;
var entityProperties = entity.GetType().GetProperties();
foreach (var attr in contextEntity.Relationships)
{
entity = attr.IsHasOne
? SetHasOneRelationship(entity, entityProperties, (HasOneAttribute)attr, contextEntity, relationships)
: SetHasManyRelationship(entity, entityProperties, attr, contextEntity, relationships);
}
return entity;
}
private object SetHasOneRelationship(object entity,
PropertyInfo[] entityProperties,
HasOneAttribute attr,
ContextEntity contextEntity,
Dictionary<string, RelationshipData> relationships)
{
var relationshipName = attr.PublicRelationshipName;
if (relationships.TryGetValue(relationshipName, out RelationshipData relationshipData))
{
var relationshipAttr = _jsonApiContext.RequestEntity.Relationships
.SingleOrDefault(r => r.PublicRelationshipName == relationshipName);
if (relationshipAttr == null)
throw new JsonApiException(400, $"{_jsonApiContext.RequestEntity.EntityName} does not contain a relationship '{relationshipName}'");
var rio = (ResourceIdentifierObject)relationshipData.ExposedData;
var foreignKey = attr.IdentifiablePropertyName;
var entityProperty = entityProperties.FirstOrDefault(p => p.Name == foreignKey);
if (entityProperty == null && rio != null)
throw new JsonApiException(400, $"{contextEntity.EntityType.Name} does not contain a foreign key property '{foreignKey}' for has one relationship '{attr.InternalRelationshipName}'");
if (entityProperty != null)
{
// e.g. PATCH /articles
// {... { "relationships":{ "Owner": { "data" :null } } } }
if (rio == null && Nullable.GetUnderlyingType(entityProperty.PropertyType) == null)
throw new JsonApiException(400, $"Cannot set required relationship identifier '{attr.IdentifiablePropertyName}' to null.");
var newValue = rio?.Id ?? null;
var convertedValue = TypeHelper.ConvertType(newValue, entityProperty.PropertyType);
_jsonApiContext.RelationshipsToUpdate[relationshipAttr] = convertedValue;
entityProperty.SetValue(entity, convertedValue);
}
}
return entity;
}
private object SetHasManyRelationship(object entity,
PropertyInfo[] entityProperties,
RelationshipAttribute attr,
ContextEntity contextEntity,
Dictionary<string, RelationshipData> relationships)
{
var relationshipName = attr.PublicRelationshipName;
if (relationships.TryGetValue(relationshipName, out RelationshipData relationshipData))
{
var data = (List<ResourceIdentifierObject>)relationshipData.ExposedData;
if (data == null) return entity;
var relationshipShells = relationshipData.ManyData.Select(r =>
{
var instance = attr.Type.New<IIdentifiable>();
instance.StringId = r.Id;
return instance;
});
var convertedCollection = TypeHelper.ConvertCollection(relationshipShells, attr.Type);
attr.SetValue(entity, convertedCollection);
_jsonApiContext.HasManyRelationshipPointers.Add(attr.Type, convertedCollection);
}
return entity;
}
}
}