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}";
    }
}
相关推荐
Chandler2419 小时前
Go语言:json 作用和语法
开发语言·golang·json
Hfc.1 天前
docker-daemon.json
docker·容器·json
UpUpUp……2 天前
Linux--JsonCpp
linux·运维·服务器·c++·笔记·json
wtsolutions3 天前
Excel-to-JSON插件专业版功能详解:让Excel数据转换更灵活
json·excel·excel-to-json·wtsolutions·专业版
kerryYG3 天前
使用JMETER中的JSON提取器实现接口关联
jmeter·json
柯ran4 天前
JSON|cJSON 介绍以及具体项目编写
c语言·链表·json·github
乐言3615 天前
Jmeter中的Json提取器如何使用?
jmeter·json
北海有初拥5 天前
【从零实现JsonRpc框架#1】Json库介绍
json
GalenWu5 天前
对象转换为 JSON 字符串(或反向解析)
前端·javascript·微信小程序·json
致于数据科学家的小陈5 天前
Go 层级菜单树转 json 处理
python·go·json·菜单树·菜单权限·children