-
Notifications
You must be signed in to change notification settings - Fork 11
/
CustomTypeMapper.cs
50 lines (43 loc) · 1.85 KB
/
CustomTypeMapper.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
using Friflo.Json.Burst;
using Friflo.Json.Fliox.Mapper;
using Friflo.Json.Fliox.Mapper.Map;
using Friflo.Json.Fliox.Schema.Definition;
using NUnit.Framework;
using static NUnit.Framework.Assert;
namespace Friflo.Json.Tests.Common.Examples.Mapper
{
// Custom type as an example to split tokens in a JSON value like "Hello World" into a string[]
[Fliox.TypeMapper(typeof(StringTokenMapper))]
public class StringTokens {
public string[] tokens;
}
public class StringTokenMapper : TypeMapper<StringTokens>
{
public override bool IsNull(ref StringTokens value) => value == null;
public override void Write(ref Writer writer, StringTokens value) {
writer.WriteString(string.Join(" ", value.tokens));
}
public override StringTokens Read(ref Reader reader, StringTokens slot, out bool success) {
if (reader.parser.Event != JsonEvent.ValueString)
return reader.HandleEvent(this, out success);
string value = reader.parser.value.AsString();
if (value.Contains(","))
return reader.ErrorMsg<StringTokens>("Invalid separator in token value", value, out success);
success = true;
return new StringTokens { tokens = value.Split(' ')};
}
}
public class CustomTypeMapper
{
[Test]
public void Run() {
string json = "\"Hello World 🌎\""; // valid JSON :) - but unusual to use only a single value
using (var mapper = new ObjectMapper()) {
StringTokens result = mapper.Read<StringTokens>(json);
AreEqual(new [] {"Hello", "World", "🌎"}, result.tokens);
var jsonResult = mapper.Write(result);
AreEqual(json, jsonResult);
}
}
}
}