【问题标题】:Generate JSON from Dictionary<Path, Value>从 Dictionary<Path, Value> 生成 JSON
【发布时间】:2020-03-24 01:10:13
【问题描述】:

我有字典,其中包含 json 路径和值:

Logging.Console.IncludeScopes = true
Logging.LogLevel.Microsoft = "Warning"
Logging.LogLevel.System= "Warning"
Sort.TypeOrder = "asc"

我想从这本词典生成 json。

{
  "Logging": {
    "Console": {
      "IncludeScopes": true
    },
    "LogLevel": {
      "Microsoft": "Warning",
      "System": "Warning"
    }
  },
  "Sort": {
    "TypeOrder": [
      "asc"
    ]
  }
}

我怎样才能做到这一点?

【问题讨论】:

  • 不完全是你想要的,但也许这会给你一个想法:stackoverflow.com/q/4861138/6996150
  • 对象可以通过像NewtonSoft.Json这样的任何工具开箱即用地生成,这里的问题TypeOrder是如何转换为数组的?是否可以更新现有的类结构以在属性或类上添加 JsonConverter 属性?
  • @johey 这是关于从简单的键值字典生成 json,我在键中有路径。
  • @PavelAnikhouski 我看过,但这不是我想要的。

标签: c# json json.net


【解决方案1】:

您不能序列化整个 Logging 对象。我的建议是为日志设置创建一个自定义类,将它用于设置日志和输出 JSON。

public class LoggingSettings
{
    public bool includeScopes;
    public LogLevel logLevel;
    public int day;
}

var settings = new LoggingSettings
        {
            includeScopes = true,
            typeOrder = "asc",
            logLevel = new LogLevel
            {
                microsoft = "Warning",
                system = "Warning"
            }
        };

序列化:

var json = new JavaScriptSerializer().Serialize(settings);
Console.WriteLine(json);

设置日志时使用:

Logging.Console.IncludeScopes = settings.includeScopes;
Logging.LogLevel.Microsoft = settings.logLevel.Microsoft;
Logging.LogLevel.System= settings.logLevel.System;
Sort.TypeOrder = settings.typeOrder;

【讨论】:

  • 我说的是字典,不是对象。 Logging.Console.IncludeScopes 是一个键,true 是它在 Dictionary 中的一个值。
  • @Dadroid 他说你不应该使用字典进行序列化,因为它不会做你想做的事情。
【解决方案2】:

由于您的密钥包含 Jobject 的动态路径,因此您可以使用递归函数来实现这一点。

最后序列化应该产生所需 json 的输出字典。

看这里

private static void CreateJSONFromDictionary(string[] keys, int index, string value, IDictionary<string, object> dict)
{
    var key = keys[index];

    if (keys.Length > index + 1)
    {
        object childObj;
        IDictionary<string, object> nestedDict;
        if (dict.TryGetValue(key, out childObj))
        {
            nestedDict = (IDictionary<string, object>)childObj;
        }
        else
        {
            nestedDict = new Dictionary<string, object>();
            dict[key] = nestedDict;
        }

        CreateJSONFromDictionary(keys, index + 1, value, nestedDict);

    }
    else
    {
        dict[key] = value;
    }
}

使用这个

var output = new Dictionary<string, object>();

foreach (var kvp in dict)
{
     var keys = kvp.Key.Split('.');
     CreateJSONFromDictionary(keys, 0, kvp.Value, output);
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-09-27
    • 1970-01-01
    • 1970-01-01
    • 2021-09-12
    • 2021-08-22
    相关资源
    最近更新 更多