source: binary-improvements/MapRendering/API/GetEntityListAbs.cs@ 489

Last change on this file since 489 was 455, checked in by alloc, 16 months ago

25_30_44

  • Got rid (mostly) of custom JSON serialization
  • Some code cleanup
File size: 1.7 KB
Line 
1using System;
2using System.Collections.Generic;
3using JetBrains.Annotations;
4using Utf8Json;
5using Webserver;
6using Webserver.WebAPI;
7
8namespace AllocsFixes.WebAPIs {
9 [UsedImplicitly]
10 internal abstract class GetEntityListAbs<T> : AbsWebAPI where T : EntityAlive {
11 private static readonly byte[] jsonKeyId = JsonWriter.GetEncodedPropertyNameWithBeginObject ("id");
12 private static readonly byte[] jsonKeyName = JsonWriter.GetEncodedPropertyNameWithPrefixValueSeparator ("name");
13 private static readonly byte[] jsonKeyPosition = JsonWriter.GetEncodedPropertyNameWithPrefixValueSeparator ("position");
14
15 private readonly List<T> entities = new List<T> ();
16 private readonly Action<List<T>> getterMethod;
17
18
19 protected GetEntityListAbs (Action<List<T>> _getterMethod) {
20 getterMethod = _getterMethod;
21 }
22
23 public override void HandleRequest (RequestContext _context) {
24 JsonWriter writer = new JsonWriter ();
25 writer.WriteBeginArray ();
26
27 getterMethod (entities);
28 for (int i = 0; i < entities.Count; i++) {
29 T entity = entities [i];
30 Vector3i position = new Vector3i (entity.GetPosition ());
31
32 if (i > 0) {
33 writer.WriteValueSeparator ();
34 }
35
36 writer.WriteRaw (jsonKeyId);
37 writer.WriteInt32 (entity.entityId);
38
39 writer.WriteRaw (jsonKeyName);
40 if (!string.IsNullOrEmpty (entity.EntityName)) {
41 writer.WriteString (entity.EntityName);
42 } else {
43 writer.WriteString ($"entity class #{entity.entityClass}");
44 }
45
46 writer.WriteRaw (jsonKeyPosition);
47 JsonCommons.WriteVector3I (ref writer, position);
48
49 writer.WriteEndObject ();
50 }
51
52 writer.WriteEndArray ();
53 WebUtils.WriteJsonData (_context.Response, ref writer);
54 }
55 }
56}
Note: See TracBrowser for help on using the repository browser.