C# 使用JSON补丁向字典添加值 概述

C# 使用JSON补丁向字典添加值 概述,c#,json-patch,C#,Json Patch,我正在尝试使用ASP.NET内核编写一个web服务,它允许客户端查询和修改微控制器的状态。该微控制器包含许多我在应用程序中建模的系统-例如,PWM系统、执行器输入系统等 这些系统的组件都具有特定的属性,可以使用请求查询或修改这些属性。例如,可以使用带有{“op”:“replace”,“path”:/pwms/3/enabled”,“value”:true}的HTTP请求启用micro上的第四个PWM。为了支持这一点,我使用了图书馆 我的问题是我正在尝试为一个新的“CAN数据库”系统实现JSON补

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

这些系统的组件都具有特定的属性,可以使用请求查询或修改这些属性。例如,可以使用带有
{“op”:“replace”,“path”:/pwms/3/enabled”,“value”:true}
的HTTP请求启用micro上的第四个PWM。为了支持这一点,我使用了图书馆

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

细节 下图为CAN数据库系统建模。
CanDatabase
实例在逻辑上应该包含一个形式为
IDictionary
的字典

为了支持创建新的消息定义,我的应用程序应该允许用户发送JSON补丁请求,如下所示:

{
“op”:“添加”,
“路径”:“/candb/my\u新定义”,
“价值”:{
“模板”:[“…”,“…”],
“重复率”:“…”,
"...": "...",
}
}
在这里,
my\u new\u definition
将定义名称,与
关联的对象应反序列化为
CanMessageDefinition
对象。然后应将其作为新的键值对存储在
CanDatabase
字典中

问题是
路径
应该指定一个属性路径,对于静态类型的对象,该路径应该是静态的(例外情况是,它允许引用数组元素,例如上面提到的
/pwms/3

我试过的 A.利罗伊·詹金斯方法

忘记我知道它不起作用的事实——我尝试了下面的实现(尽管我需要支持动态JSON补丁路径,但它只使用静态类型),只是为了看看会发生什么

实施

内部密封类CanDatabaseModel:DeviceComponentModel
{
公共CanDatabaseModel()
{
this.Definitions=新字典();
}
[JsonProperty(PropertyName=“candb”)]
公共IDictionary定义{get;}
...
}
测试

{
“op”:“添加”,
“路径”:“/candb/foo”,
“价值”:{
“messageId”:171,
“模板”:[17,34],
“重复率”:100,
“canPort”:0
}
}
结果

在我尝试将指定更改应用于
JsonPatchDocument
的站点上抛出了一个
InvalidCastException

地点:

var currentModelSnapshot=this.currentModelFilter(this.currentModel.Copy());
var snapshotWithChangesApplied=currentModelSnapshot.Copy();
diffDocument.ApplyTo(应用更改的快照);
例外情况:

无法将“Newtonsoft.Json.Serialization.JsonDictionaryContract”类型的对象强制转换为“Newtonsoft.Json.Serialization.JsonObjectContract”类型。

B.依赖动态JSON补丁

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

实施

内部密封类CanDatabaseModel:DeviceComponentModel
{
公共CanDatabaseModel()
{
this.Definitions=newexpandoobject();
}
[JsonProperty(PropertyName=“candb”)]
公共IDictionary定义{get;}
...
}
测试

{
“op”:“添加”,
“路径”:“/candb/foo”,
“价值”:{
“messageId”:171,
“模板”:[17,34],
“重复率”:100,
“canPort”:0
}
}
结果

进行此更改允许我的测试的这一部分在运行时不会引发异常,但JSON修补程序不知道将
反序列化为什么,导致数据作为
作业对象
而不是
CanMessageDefinition
存储在字典中:

有没有可能“告诉”JSON补丁如何反序列化信息?也许是类似于在
定义
上使用
JsonConverter
属性的东西

[JsonProperty(PropertyName=“candb”)]
[JsonConverter(…)]
公共IDictionary定义{get;}

总结
  • 我需要支持向字典添加值的JSON补丁请求
  • 我试着走纯静态路线,但失败了
  • 我尝试过使用动态JSON补丁
    • 这部分起作用,但我的数据存储为
      JObject
      类型,而不是预期的类型
    • 是否有一个属性(或其他技术)可以应用于我的属性,使其反序列化为正确的类型(而不是匿名类型)

由于似乎没有任何正式的方法来做这件事,我想出了一个临时解决方案™ (阅读:一个足够有效的解决方案,所以我可能会永远保留它)

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

更具体地说,该类重写方法,如
TrySetMember
TrySetIndex
TryGetMember
,本质上就像一个字典,只是它将所有这些操作委托给
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
}
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
}
var dataDict = JsonConvert.DeserializeObject<Dictionary<string, object>>(json);
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);
    }
    
}