forked from scriptcs/scriptcs
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathObjectSerializer.cs
More file actions
59 lines (55 loc) · 2.16 KB
/
ObjectSerializer.cs
File metadata and controls
59 lines (55 loc) · 2.16 KB
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
using System.Linq;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using ScriptCs.Contracts;
namespace ScriptCs.Hosting
{
public class ObjectSerializer : IObjectSerializer
{
private static readonly JsonSerializerSettings settings = new JsonSerializerSettings
{
Formatting = Formatting.Indented,
PreserveReferencesHandling = PreserveReferencesHandling.Objects,
ReferenceLoopHandling = ReferenceLoopHandling.Serialize,
};
public string Serialize(object value)
{
try
{
var writer = new JTokenWriter();
var serializer = JsonSerializer.Create(settings);
serializer.Serialize(writer, value);
var container = writer.Token as JContainer;
if (container != null)
{
var idProperties = container.Descendants().OfType<JProperty>().Where(d => d.Name == "$id").ToList();
if (idProperties.Any())
{
var refProperties = container.Descendants().OfType<JProperty>().Where(d => d.Name == "$ref").ToList();
if (refProperties.Any())
{
foreach (var idProperty in idProperties
.Where(idProperty => refProperties
.All(refProperty => refProperty.Value.ToString() != idProperty.Value.ToString())))
{
idProperty.Remove();
}
}
else
{
foreach (var idProperty in idProperties)
{
idProperty.Remove();
}
}
}
}
return writer.Token.ToString();
}
catch (JsonSerializationException)
{
return string.Format("Couldn't serialize a returned instance of {0}", value.GetType());
}
}
}
}