about summary refs log tree commit diff
path: root/MatrixRoomUtils.Core/Extensions/JsonElementExtensions.cs
blob: 36da6441d62a49f457c4ffdb47811167f464c973 (plain) (blame)
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
using System.Diagnostics.CodeAnalysis;
using System.Reflection;
using System.Text.Json;
using System.Text.Json.Nodes;
using System.Text.Json.Serialization;

namespace MatrixRoomUtils.Core.Extensions;

public static class JsonElementExtensions {
    public static bool FindExtraJsonElementFields([DisallowNull] this JsonElement? res, Type t) {
        var props = t.GetProperties();
        var unknownPropertyFound = false;
        foreach (var field in res.Value.EnumerateObject()) {
            if (props.Any(x => x.GetCustomAttribute<JsonPropertyNameAttribute>()?.Name == field.Name)) continue;
            Console.WriteLine($"[!!] Unknown property {field.Name} in {t.Name}!");
            unknownPropertyFound = true;
        }

        if (unknownPropertyFound) Console.WriteLine(res.Value.ToJson());

        return unknownPropertyFound;
    }
    public static bool FindExtraJsonObjectFields([DisallowNull] this JsonObject? res, Type t) {
        var props = t.GetProperties();
        var unknownPropertyFound = false;
        foreach (var field in res) {
            if (props.Any(x => x.GetCustomAttribute<JsonPropertyNameAttribute>()?.Name == field.Key)) continue;
            Console.WriteLine($"[!!] Unknown property {field.Key} in {t.Name}!");
            unknownPropertyFound = true;
            // foreach (var propertyInfo in props) {
            //     Console.WriteLine($"[!!] Known property {propertyInfo.GetCustomAttribute<JsonPropertyNameAttribute>()?.Name} in {t.Name}!");
            // }
        }

        if (unknownPropertyFound) Console.WriteLine(res.ToJson());

        return unknownPropertyFound;
    }
}