使用JSON Patch向字典中添加值

15

概述

我正在尝试使用ASP.NET Core编写一个Web服务,允许客户端查询和修改微控制器的状态。该微控制器包含多个系统,在我的应用程序中进行建模 - 例如,PWM系统、执行器输入系统等。

这些系统的组件都有特定的属性,可以使用JSON patch请求进行查询或修改。例如,可以使用携带{"op":"replace", "path":"/pwms/3/enabled", "value":true}的HTTP请求启用微控制器上的第4个PWM。为了支持这一点,我正在使用AspNetCore.JsonPatch库。

我的问题是,我正在尝试为新的“CAN数据库”系统实现JSON Patch支持,该系统在逻辑上应将定义名称映射到特定的CAN消息定义,但我不确定如何去做。

详细信息

下面的图表建模了CAN数据库系统。一个CanDatabase实例应该在逻辑上包含一个这样的字典:IDictionary<string, CanMessageDefinition>

CAN Database system model

为了支持创建新的消息定义,我的应用程序应该允许用户发送这样的JSON patch请求:

{
    "op": "add",
    "path": "/candb/my_new_definition",
    "value": {
        "template": ["...", "..."],
        "repeatRate": "...",
        "...": "...",
    }
}

在这里,my_new_definition将定义名称的定义,并且与value关联的对象应反序列化为CanMessageDefinition对象。然后,应将其作为新的键值对存储在CanDatabase字典中。

问题在于,path应该指定一个属性路径,对于静态类型的对象,它是...静态的(唯一的例外是它允许引用数组元素,例如/pwms/3)。

我尝试过的方法

A. Leeroy Jenkins方法

忘记我知道它行不通的事实-我尝试了下面的实现(仅使用静态类型,尽管我需要支持动态JSON Patch路径),只是为了看看会发生什么。

实现

internal sealed class CanDatabaseModel : DeviceComponentModel<CanDatabaseModel>
{
    public CanDatabaseModel()
    {
        this.Definitions = new Dictionary<string, CanMessageDefinition>();
    }

    [JsonProperty(PropertyName = "candb")]
    public IDictionary<string, CanMessageDefinition> Definitions { get; }

    ...
}

测试

{
    "op": "add",
    "path": "/candb/foo",
    "value": {
        "messageId": 171,
        "template": [17, 34],
        "repeatRate": 100,
        "canPort": 0
    }
}

结果

在我试图将指定的更改应用于 JsonPatchDocument 时,会在该位置引发 InvalidCastException

位置:

var currentModelSnapshot = this.currentModelFilter(this.currentModel.Copy());
var snapshotWithChangesApplied = currentModelSnapshot.Copy();
diffDocument.ApplyTo(snapshotWithChangesApplied);

异常:

Unable to cast object of type 'Newtonsoft.Json.Serialization.JsonDictionaryContract' to type 'Newtonsoft.Json.Serialization.JsonObjectContract'.

B. 依赖于动态JSON Patching

一种更有前途的攻击计划似乎是依赖于动态JSON patching,它涉及对ExpandoObject实例执行补丁操作。这允许您使用JSON补丁文档添加、删除或替换属性,因为您正在处理动态类型的对象。

实现

internal sealed class CanDatabaseModel : DeviceComponentModel<CanDatabaseModel>
{
    public CanDatabaseModel()
    {
        this.Definitions = new ExpandoObject();
    }

    [JsonProperty(PropertyName = "candb")]
    public IDictionary<string, object> Definitions { get; }

    ...
}

测试

{
    "op": "add",
    "path": "/candb/foo",
    "value": {
        "messageId": 171,
        "template": [17, 34],
        "repeatRate": 100,
        "canPort": 0
    }
}

结果

进行这个变更后,我的测试的这一部分能够正常运行而不会产生异常,但是JSON Patch无法知道怎样反序列化value,导致数据被存储在字典中的JObject而不是CanMessageDefinition中:

方案B的结果

有没有可能通过某种方式“告诉”JSON Patch如何反序列化信息?也许可以在Definitions上使用JsonConverter属性之类的东西?

[JsonProperty(PropertyName = "candb")]
[JsonConverter(...)]
public IDictionary<string, object> Definitions { get; }

总结

  • 我需要支持添加值到字典的JSON patch请求
  • 我曾尝试使用纯静态方法,但失败了
  • 我尝试使用动态JSON补丁
    • 这部分成功了,但我的数据被存储为JObject类型而非预期的类型
    • 是否有属性(或其他技术)可以应用于我的属性,以便使其反序列化为正确的类型(而不是匿名类型)?


实现自定义的JSON反序列化器似乎是一个可行的解决方案。你能详细说明一下value对象中的template吗?我们可以将messageIdtemplate移动到父对象中吗? - Ankit
@Ankit template 表示 CAN 消息负载(0-8 字节),因此它将是一个整数数组。messageIdtemplate 必须保持不变,因为请求需要遵循 RFC 6902 中描述的 JSON Patch 模式。 - Tagc
你想出了解决方案吗?这是一个有趣的场景,我已经收藏了它,等我从工作中抽出一些时间来处理。 - Ankit
@Ankit 还没有。我正在使用一个临时解决方法(将 PropertyChanged 事件处理程序注册到 ExpandoObject,手动将新的 JObject 转换为 CanMessageDefinition)。 - Tagc
Leeeeroooooooy! :) - ToddBFisher
我认为您无法反序列化IDictionary<T, K>。您是否尝试使用Dictionary<T, K>?我正在使用它,没有遇到任何问题。 - Sinaesthetic
2个回答

3

由于似乎没有官方的方法来做到这一点,我想出了一个临时解决方案™(即:一个足够好用的解决方案,所以我可能会一直使用它)。

为了让JSON Patch处理类似字典的操作,我创建了一个名为DynamicDeserialisationStore的类,该类继承自DynamicObject并利用JSON Patch对动态对象的支持。

更具体地说,该类重写了TrySetMemberTrySetIndexTryGetMember等方法,以基本上像字典一样运作,只是将所有这些操作委托给其构造函数提供的回调函数。

实现

以下代码提供了DynamicDeserialisationStore的实现。它实现了IDictionary<string,object>(这是JSON Patch要求与动态对象一起工作的签名),但我仅实现了我需要的最少量的方法。

JSON Patch对动态对象的支持问题在于它将属性设置为JObject实例,即当设置静态属性时它不会自动执行反序列化,因为它无法推断类型。 DynamicDeserialisationStore是根据它将尝试自动反序列化这些JObject实例的对象类型进行参数化的。
该类接受回调来处理基本字典操作,而不是维护内部字典本身,因为在我的“真实”系统模型代码中,我实际上不使用字典(由于各种原因),我只是让它看起来像客户端使用字典一样。
internal sealed class DynamicDeserialisationStore<T> : DynamicObject, IDictionary<string, object> where T : class
{
    private readonly Action<string, T> storeValue;
    private readonly Func<string, bool> removeValue;
    private readonly Func<string, T> retrieveValue;
    private readonly Func<IEnumerable<string>> retrieveKeys;

    public DynamicDeserialisationStore(
        Action<string, T> storeValue,
        Func<string, bool> removeValue,
        Func<string, T> retrieveValue,
        Func<IEnumerable<string>> retrieveKeys)
    {
        this.storeValue = storeValue;
        this.removeValue = removeValue;
        this.retrieveValue = retrieveValue;
        this.retrieveKeys = retrieveKeys;
    }

    public int Count
    {
        get
        {
            return this.retrieveKeys().Count();
        }
    }

    private IReadOnlyDictionary<string, T> AsDict
    {
        get
        {
            return (from key in this.retrieveKeys()
                    let value = this.retrieveValue(key)
                    select new { key, value })
                    .ToDictionary(it => it.key, it => it.value);
        }
    }

    public override bool TrySetIndex(SetIndexBinder binder, object[] indexes, object value)
    {
        if (indexes.Length == 1 && indexes[0] is string && value is JObject)
        {
            return this.TryUpdateValue(indexes[0] as string, value);
        }

        return base.TrySetIndex(binder, indexes, value);
    }

    public override bool TryGetIndex(GetIndexBinder binder, object[] indexes, out object result)
    {
        if (indexes.Length == 1 && indexes[0] is string)
        {
            try
            {
                result = this.retrieveValue(indexes[0] as string);
                return true;
            }
            catch (KeyNotFoundException)
            {
                // Pass through.
            }
        }

        return base.TryGetIndex(binder, indexes, out result);
    }

    public override bool TrySetMember(SetMemberBinder binder, object value)
    {
        return this.TryUpdateValue(binder.Name, value);
    }

    public override bool TryGetMember(GetMemberBinder binder, out object result)
    {
        try
        {
            result = this.retrieveValue(binder.Name);
            return true;
        }
        catch (KeyNotFoundException)
        {
            return base.TryGetMember(binder, out result);
        }
    }

    private bool TryUpdateValue(string name, object value)
    {
        JObject jObject = value as JObject;
        T tObject = value as T;

        if (jObject != null)
        {
            this.storeValue(name, jObject.ToObject<T>());
            return true;
        }
        else if (tObject != null)
        {
            this.storeValue(name, tObject);
            return true;
        }

        return false;
    }

    object IDictionary<string, object>.this[string key]
    {
        get
        {
            return this.retrieveValue(key);
        }

        set
        {
            this.TryUpdateValue(key, value);
        }
    }

    public IEnumerator<KeyValuePair<string, object>> GetEnumerator()
    {
        return this.AsDict.ToDictionary(it => it.Key, it => it.Value as object).GetEnumerator();
    }

    public void Add(string key, object value)
    {
        this.TryUpdateValue(key, value);
    }

    public bool Remove(string key)
    {
        return this.removeValue(key);
    }

    #region Unused methods
    bool ICollection<KeyValuePair<string, object>>.IsReadOnly
    {
        get
        {
            throw new NotImplementedException();
        }
    }

    ICollection<string> IDictionary<string, object>.Keys
    {
        get
        {
            throw new NotImplementedException();
        }
    }

    ICollection<object> IDictionary<string, object>.Values
    {
        get
        {
            throw new NotImplementedException();
        }
    }

    void ICollection<KeyValuePair<string, object>>.Add(KeyValuePair<string, object> item)
    {
        throw new NotImplementedException();
    }

    void ICollection<KeyValuePair<string, object>>.Clear()
    {
        throw new NotImplementedException();
    }

    bool ICollection<KeyValuePair<string, object>>.Contains(KeyValuePair<string, object> item)
    {
        throw new NotImplementedException();
    }

    bool IDictionary<string, object>.ContainsKey(string key)
    {
        throw new NotImplementedException();
    }

    void ICollection<KeyValuePair<string, object>>.CopyTo(KeyValuePair<string, object>[] array, int arrayIndex)
    {
        throw new NotImplementedException();
    }

    IEnumerator IEnumerable.GetEnumerator()
    {
        throw new NotImplementedException();
    }

    bool ICollection<KeyValuePair<string, object>>.Remove(KeyValuePair<string, object> item)
    {
        throw new NotImplementedException();
    }

    bool IDictionary<string, object>.TryGetValue(string key, out object value)
    {
        throw new NotImplementedException();
    }
    #endregion
}

测试

下面提供了该类的测试。我创建了一个模拟系统模型(见图像),并对其执行了各种JSON Patch操作。

这里是代码:

public class DynamicDeserialisationStoreTests
{
    private readonly FooSystemModel fooSystem;

    public DynamicDeserialisationStoreTests()
    {
        this.fooSystem = new FooSystemModel();
    }

    [Fact]
    public void Store_Should_Handle_Adding_Keyed_Model()
    {
        // GIVEN the foo system currently contains no foos.
        this.fooSystem.Foos.ShouldBeEmpty();

        // GIVEN a patch document to store a foo called "test".
        var request = "{\"op\":\"add\",\"path\":\"/foos/test\",\"value\":{\"number\":3,\"bazzed\":true}}";
        var operation = JsonConvert.DeserializeObject<Operation<FooSystemModel>>(request);
        var patchDocument = new JsonPatchDocument<FooSystemModel>(
            new[] { operation }.ToList(),
            new CamelCasePropertyNamesContractResolver());

        // WHEN we apply this patch document to the foo system model.
        patchDocument.ApplyTo(this.fooSystem);

        // THEN the system model should now contain a new foo called "test" with the expected properties.
        this.fooSystem.Foos.ShouldHaveSingleItem();
        FooModel foo = this.fooSystem.Foos["test"] as FooModel;
        foo.Number.ShouldBe(3);
        foo.IsBazzed.ShouldBeTrue();
    }

    [Fact]
    public void Store_Should_Handle_Removing_Keyed_Model()
    {
        // GIVEN the foo system currently contains a foo.
        var testFoo = new FooModel { Number = 3, IsBazzed = true };
        this.fooSystem.Foos["test"] = testFoo;

        // GIVEN a patch document to remove a foo called "test".
        var request = "{\"op\":\"remove\",\"path\":\"/foos/test\"}";
        var operation = JsonConvert.DeserializeObject<Operation<FooSystemModel>>(request);
        var patchDocument = new JsonPatchDocument<FooSystemModel>(
            new[] { operation }.ToList(),
            new CamelCasePropertyNamesContractResolver());

        // WHEN we apply this patch document to the foo system model.
        patchDocument.ApplyTo(this.fooSystem);

        // THEN the system model should be empty.
        this.fooSystem.Foos.ShouldBeEmpty();
    }

    [Fact]
    public void Store_Should_Handle_Modifying_Keyed_Model()
    {
        // GIVEN the foo system currently contains a foo.
        var originalFoo = new FooModel { Number = 3, IsBazzed = true };
        this.fooSystem.Foos["test"] = originalFoo;

        // GIVEN a patch document to modify a foo called "test".
        var request = "{\"op\":\"replace\",\"path\":\"/foos/test\", \"value\":{\"number\":6,\"bazzed\":false}}";
        var operation = JsonConvert.DeserializeObject<Operation<FooSystemModel>>(request);
        var patchDocument = new JsonPatchDocument<FooSystemModel>(
            new[] { operation }.ToList(),
            new CamelCasePropertyNamesContractResolver());

        // WHEN we apply this patch document to the foo system model.
        patchDocument.ApplyTo(this.fooSystem);

        // THEN the system model should contain a modified "test" foo.
        this.fooSystem.Foos.ShouldHaveSingleItem();
        FooModel foo = this.fooSystem.Foos["test"] as FooModel;
        foo.Number.ShouldBe(6);
        foo.IsBazzed.ShouldBeFalse();
    }

    #region Mock Models
    private class FooModel
    {
        [JsonProperty(PropertyName = "number")]
        public int Number { get; set; }

        [JsonProperty(PropertyName = "bazzed")]
        public bool IsBazzed { get; set; }
    }

    private class FooSystemModel
    {
        private readonly IDictionary<string, FooModel> foos;

        public FooSystemModel()
        {
            this.foos = new Dictionary<string, FooModel>();
            this.Foos = new DynamicDeserialisationStore<FooModel>(
                storeValue: (name, foo) => this.foos[name] = foo,
                removeValue: name => this.foos.Remove(name),
                retrieveValue: name => this.foos[name],
                retrieveKeys: () => this.foos.Keys);
        }

        [JsonProperty(PropertyName = "foos")]
        public IDictionary<string, object> Foos { get; }
    }
    #endregion
}

0
你可以将接收到的Json反序列化为一个对象:
var dataDict = JsonConvert.DeserializeObject<Dictionary<string, object>>(json);

遍历它,将你想要修补的KeyValuePairs的值转换并强制转换为目标类型CanMessageDefinition:

Dictionary<string, CanMessageDefinition> updateData = new Dictionary<string, CanMessageDefinition>();
foreach (var record in dataDict)
{
    CanMessageDefinition recordValue = (CanMessageDefinition)record.Value;
    if (yourExistingRecord.KeyAttributes.Keys.Contains(record.Key) && (!yourExistingRecord.KeyAttributes.Values.Equals(record.Value)))
    { 
        updateData.Add(record.Key, recordValue);
    }
    
}

然后将您的对象保存到数据库中即可。

另一种选择是像你提到的那样在JsonConverter中完成。干杯!


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接