让我们说JSON对象是空的:
String obj1 = "{}";
有没有办法修补它并使用C#强制创建丢失的路径? 经过这样的补丁之后:
{ "op": "add", "path": "/a/b", "value": "foo" },
结果将是:{ a: { b: "foo" } }
答案 0 :(得分:0)
不确定你的问题究竟是什么,如果我错了,你可以使用System.Dynamic.ExpandoObject或使用IDictionary在C#中创建那些自定义json对象,或者在我的例子中创建这两个对象(例如我懒惰) 正如在评论中所说,这更像是一个解析,而不是一个变换:
using System;
using System.Collections.Generic;
using System.Linq;
using Newtonsoft.Json;
namespace ExpandoObject
{
class Program
{
static void Main(string[] args)
{
string stringObj;
stringObj = "{\"op\": \"add\", \"path\": \"/a/b\", \"value\": \"foo\"}";
Console.WriteLine(JsonConvert.SerializeObject(GetObjectPatchResult(stringObj)));
stringObj = "{\"op\": \"add\", \"path\": \"/a/b/c/d/e/f/g/h/i/j\", \"value\": \"foo\"}";
Console.WriteLine(JsonConvert.SerializeObject(GetObjectPatchResult(stringObj)));
}
private static object GetObjectPatchResult(string param)
{
dynamic expando = new System.Dynamic.ExpandoObject();
var result = (IDictionary<string, object>)expando;
var parchObject = JsonConvert.DeserializeObject<PatchObject>(param);
var level = result;
int i = 0;
foreach (var path in parchObject.Path.Split('/'))
{
i++;
if (string.IsNullOrEmpty(path)) continue;
dynamic pathExpando = new System.Dynamic.ExpandoObject();
level[path] = (IDictionary<string, object>)pathExpando;
if (i < parchObject.Path.Split('/').Count())
{
level = (IDictionary<string, object>)level[path];
}
else
{
level[path] = parchObject.Value;
}
}
return result;
}
}
public class PatchObject
{
public string Op { get; set; }
public string Path { get; set; }
public string Value { get; set; }
}
}
结果:
{ “一”:{ “B”: “foo” 的}}
{ “一”:{ “B”:{ “C”:{ “d”:{ “E”:{ “F”:{ “克”:{ “H”:{ “I”:{” J “:” foo“的}}}}}}}}}}
按任意键继续。 。