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}";
    }
}
相关推荐
亚林瓜子11 小时前
Jackson注解屏蔽某些字段读取权限
spring·json·jackson
不惑_17 小时前
最佳实践 · 如何高效索引MySQL JSON字段
java·mysql·json
天上掉下来个程小白1 天前
请求响应-05.请求-日期参数&JSON参数
spring boot·json
敲代码不忘补水1 天前
Python Pickle 与 JSON 序列化详解:存储、反序列化与对比
开发语言·python·json
jackletter2 天前
c#:System.Text.Json 的使用四(如何忽略[JsonPropertyName])
c#·json·序列化
A 八方2 天前
Python JSON
开发语言·python·json
小故渊2 天前
JSON对象
运维·服务器·json
SelectDB技术团队2 天前
查询性能提升 10 倍、存储空间节省 65%,Apache Doris 半结构化数据分析方案及典型场景
数据结构·数据仓库·elasticsearch·log4j·json
D11_3 天前
pandas:读取各类文件方法以及爬虫时json数据保存
爬虫·python·数据分析·json·pandas
深夜吞食4 天前
项目实现:云备份③(配置文件加载模块、数据管理模块的实现)
linux·c语言·c++·json