0

假设有一个空的 JSON 对象:

String obj1 = "{}";

有没有办法修补更新它并使用 C# 强制创建丢失的路径?所以在这样的补丁之后:

{ "op": "add", "path": "/a/b", "value": "foo" },

结果将是:{ a: { b: "foo" } }

4

1 回答 1

0

不知道你的问题到底是什么,如果我错了,你可以在 C# 中使用 System.Dynamic.ExpandoObject 或使用 IDictionary 或两者创建这些自定义 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; }
    }
}

结果:

{"a":{"b":"foo"}}

{"a":{"b":{"c":{"d":{"e":{"f":{"g":{"h":{"i":{"j": “富”}}}}}}}}}}

按任意键继续 。. .

于 2016-02-23T14:16:35.727 回答