Json Flatten 扁平化Json

cs 复制代码
using System;
using System.Linq;
using System.Collections.Generic;
using JsonFlatten; // https://www.nuget.org/packages/JsonFlatten
using Newtonsoft.Json.Linq;

public class Program
{
    private static readonly string json = @"{ 'array': [ 1, 2, 3 ], 'property.with.period.in.path': true, 'number': 123, 'object': { 'a': 'b', 'c': 'd', 'e': 'f' }, 'date': '2014-01-01T23:28:56.782Z', 'string': 'Hello World', 'null': null, 'emptyString': '', 'emptyObject': {}, 'emptyArray': [] }";

    public static void Main()
    {
        JObject jObj = JObject.Parse(json);
        
        // Flatten a JObject to a dictionary. 
        // You can also use: Dictionary<string, object> flattened = new Dictionary<string, object>(jObj.Flatten());
        var flattened = jObj.Flatten();        
        WriteLine("Flattened JObject:\r\n" + ToDebugString(flattened));
        
        // Unflatten a Dictionary<string, object> to a JObject
        JObject unflattened = flattened.Unflatten();
        WriteLine("Unflattened JObject:\r\n" + ToDebugString(unflattened));
        
        WriteLine("JObject is equal to unflattened dictionary: " + JToken.DeepEquals(jObj, unflattened)); // True
        
        // Retrieve and cast an item from the dictionary
        var date = flattened.Get<DateTime>("date");
        WriteLine("\"date\" property: " + date);
        
        // Update an entry
        flattened.Set("date", date.AddDays(5));
        WriteLine("Updated \"date\" property: " + flattened.Get<DateTime>("date")); // 1/6/2014 11:28:56 PM
        
        // Flattened a JObject and remove any JSON properties that have null or empty values e.g. null, "", {}, or []
        var flattenedWithoutEmpty = jObj.Flatten(includeNullAndEmptyValues: false);
        WriteLine("Flattened JObject without empty properties:\r\n" + ToDebugString(flattenedWithoutEmpty));
        WriteLine("Unflattened JObject without empty properties:\r\n" + flattenedWithoutEmpty.Unflatten().ToString());
    }
    
    public static Action<object> WriteLine = (msg) => Console.WriteLine("\r\n" + msg.ToString() + "\r\n");

    public static string ToDebugString<TKey, TValue>(IDictionary<TKey, TValue> dictionary)
    {
        return "{\r\n\t" + string.Join(",\r\n\t", dictionary.Select(kv => kv.Key + " = " + kv.Value).ToArray()) + "\r\n}";
    }
}
相关推荐
会篮球的程序猿21 小时前
html+canvas+thikphp 可视化工具拖拽、编辑生成JSON,渲染成海报图片 完全自定义,支持选择,文字背景色
前端·html·json
倚肆21 小时前
Hutool-json 库完整指南
java·json
q***23921 天前
MySQL JSON数据类型全解析(JSON datatype and functions)
android·mysql·json
i_am_a_div_日积月累_3 天前
JSON数据转Excel
json·excel·css3
www_stdio4 天前
用 localStorage 打造本地待办清单:一个轻量级的前端实践
javascript·css·json
Jonathan Star4 天前
JSON-RPC 2.0 详解
qt·rpc·json
还算善良_5 天前
【XML生成】根据JSON格式化的报文,动态生成XML
xml·json
涛涛讲AI6 天前
被 JSON 格式折磨?1 个快捷键让 JSON-handle 秒启动,开发者必看!
json
韩仔搭建6 天前
Cocos Creator 项目配置 JSON 最佳实践
json
曼巴UE56 天前
JSON Reader
java·服务器·json