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}";
    }
}
相关推荐
qq_448011165 小时前
python HTTP请求同时返回为JSON的异常处理
python·http·json
未来魔导7 小时前
go语言中json操作总结(下)
数据分析·go·json
清水白石00810 小时前
《Python × 数据库:用 SQLAlchemy 解锁高效 ORM 编程的艺术》
开发语言·python·json
真上帝的左手12 小时前
6. 接口-专栏说明
json·restful
Leoysq16 小时前
UGUI 读取JSON动态克隆背包道具信息
json
望外追晚17 小时前
mask_color_map.json丢失,导致分割标签.png无法导入X-Anylabeling的解决办法
人工智能·计算机视觉·json·paddlepaddle
咘噜biu18 小时前
Java 安全的打印对象数据到日志
java·json·日志·脱敏
未来魔导1 天前
go语言中json操作总结
数据分析·go·json
青鱼入云1 天前
@JsonValue和@JsonCreator介绍
json·jackson
这儿有一堆花2 天前
JSON 与 MongoDB:直存对象的便利与隐性代价
数据库·mongodb·json