2

servicestack.text 中是否有将两个 json 字符串合并为一个 dto 的机制?

用例是将来自多个来源的复杂设置合并到一个设置文件中

IE

{“废话”:{“参数”:{“默认”:“酒吧”,“杂项”:“0”,}}}

{ "blah": { "params": { "value": "val", "misc": "1", } } }

变成

{ "blah": { "params": { "default": "bar", "value": "val", "misc": "1", } } }

谢谢

4

2 回答 2

1

请注意结尾的逗号,因为它不是有效的 JSON。但是您可以使用ServiceStack 的 JSON 序列化器的动态 API来执行此操作:

var json1 = "{\"blah\":{\"params\":{\"default\":\"bar\", \"misc\": \"0\" } } }";
var json2 = "{\"blah\":{\"params\":{\"value\":\"val\", \"misc\": \"1\" } } }";

var jsonObj = JsonObject.Parse(json1);
var jsonParams =jsonObj.Object("blah").Object("params");

foreach (var entry in JsonObject.Parse(json2).Object("blah").Object("params"))
{
    jsonParams[entry.Key] = entry.Value;
}

var to = new { blah = new { @params = jsonParams } };

to.ToJson().Print();

这将输出:

{"blah":{"params":{"default":"bar","misc":"1","value":"val"}}}
于 2012-09-21T21:54:50.963 回答
0

好吧,如果你不打算使用 JsonArrays,上面的解决方案可以用递归方式编写:

public static JsonObject Merge(JsonObject @this, JsonObject that) {
  foreach (var entry in that) {
    var exists = @this.ContainsKey (entry.Key);
    if (exists) {
      var otherThis = JsonObject.Parse(@this.GetUnescaped (entry.Key));
      var otherThat = JsonObject.Parse(that.GetUnescaped (entry.Key));
      @this [entry.Key] = Merge (otherThis, otherThat).ToJson ();
    } else {
      @this [entry.Key] = entry.Value;
    }
  }
  return @this;
}
于 2014-05-19T12:59:44.913 回答