58 lines
1.9 KiB
D
58 lines
1.9 KiB
D
|
module shared_utils.server_status;
|
||
|
|
||
|
import std.json;
|
||
|
|
||
|
struct ServerStatus {
|
||
|
string identifier = null;
|
||
|
string name = null;
|
||
|
bool online = false;
|
||
|
int playersOnline = 0;
|
||
|
int maxPlayers = 0;
|
||
|
string[] playerNames = [];
|
||
|
|
||
|
JSONValue toJsonObject() {
|
||
|
JSONValue obj = JSONValue.emptyObject;
|
||
|
obj.object["identifier"] = JSONValue(identifier);
|
||
|
obj.object["name"] = JSONValue(name);
|
||
|
obj.object["online"] = JSONValue(online);
|
||
|
obj.object["playersOnline"] = JSONValue(playersOnline);
|
||
|
obj.object["maxPlayers"] = JSONValue(maxPlayers);
|
||
|
obj.object["playerNames"] = JSONValue.emptyArray;
|
||
|
foreach (playerName; playerNames) {
|
||
|
obj.object["playerNames"].array ~= JSONValue(playerName);
|
||
|
}
|
||
|
return obj;
|
||
|
}
|
||
|
|
||
|
static ServerStatus fromJsonObject(JSONValue obj) {
|
||
|
if (obj.type != JSONType.OBJECT) throw new JSONException("JSON value is not an object.");
|
||
|
ServerStatus s;
|
||
|
s.identifier = obj.object["identifier"].str;
|
||
|
s.name = obj.object["name"].str;
|
||
|
s.online = obj.object["online"].boolean;
|
||
|
s.playersOnline = cast(int) obj.object["playersOnline"].integer;
|
||
|
s.maxPlayers = cast(int) obj.object["maxPlayers"].integer;
|
||
|
foreach (node; obj.object["playerNames"].array) {
|
||
|
s.playerNames ~= node.str;
|
||
|
}
|
||
|
return s;
|
||
|
}
|
||
|
}
|
||
|
|
||
|
JSONValue serializeServerStatuses(ServerStatus[] statuses) {
|
||
|
JSONValue arr = JSONValue.emptyArray;
|
||
|
foreach (s; statuses) {
|
||
|
arr.array ~= s.toJsonObject();
|
||
|
}
|
||
|
return arr;
|
||
|
}
|
||
|
|
||
|
ServerStatus[] deserializeServerStatuses(JSONValue arr) {
|
||
|
if (arr.type != JSONType.ARRAY) throw new JSONException("JSON value is not an array.");
|
||
|
ServerStatus[] statuses = new ServerStatus[arr.array.length];
|
||
|
for (size_t i = 0; i < arr.array.length; i++) {
|
||
|
statuses[i] = ServerStatus.fromJsonObject(arr.array[i]);
|
||
|
}
|
||
|
return statuses;
|
||
|
}
|