将 ExpandoObject 的内容打印为缩进字符串

Printing Contents of ExpandoObject to an Indented String

我目前正在开发一个接受 JSON 输入并使用 JSON.NET 将其反序列化为动态 ExpandoObject 的程序。然后通过一个函数,我想将它转储到另一个文本框中以显示它可能表示为 C# 对象的内容。我将如何缩进我的字符串以显示我的分层 ExpandoObject 并将其从平面数据列表转换为我可以作为字符串发送到文本框的数据树结构?

这是我正在使用的一些代码:

if (tbxJSON.Text != "")
{
        // Create an ExpandoObjectConverter in order to hold the dynamic parsed JSON.
        var converter = new ExpandoObjectConverter();
        dynamic convertedJSON = JsonConvert.DeserializeObject<ExpandoObject>(tbxJSON.Text, converter);

            tbxCSharp.Text = "";

        // Loop through the ExpandoObject and print out all of the values in the dynamic object using a recursive function.
        foreach (var property in (IDictionary<string, object>)convertedJSON)
                sb.Append(ExpandoToString(property.Value, property.Key));

        // Set C# output to contents of StringBuilder.
        tbxCSharp.Text = sb.ToString();
}

private string ExpandoToString(object propVal, string propName)
{
    string retStr = "";

    // If we are dealing with nested JSON
    if (propVal.GetType() == typeof(ExpandoObject))
    {
        // Append this object type.
        sb.Append(Indent(indentIdx) + UppercaseFirst(propName) + " " + propName + " consists of..." + Environment.NewLine);

        foreach (var prop in (IDictionary<string, object>)propVal)
        {
            if (prop.Value.GetType() == typeof(ExpandoObject))
                sb.Append(ExpandoToString(prop.Value, prop.Key));
            else
            {
                if (prop.Value.GetType() == typeof(List<dynamic>))
                {
                    // TO DO
                }
                else
                    sb.Append(ExpandoToString(prop.Value, prop.Key));
            }
        }
    }
    else 
            retStr = propVal.GetType() + " : " + propName + " = " + propVal + Environment.NewLine;

    return retStr;
}


Test JSON:
{"airline":"Oceanic","number":815,"departure":{"IATA":"SYD","time":"2004-09-22 14:55","city":"Sydney"},"arrival":{"IATA":"LAX","time":"2004-09-23 10:42","city":"Los Angeles"}}

您应该将当前缩进作为参数提供给 ExpandoToString() 方法,并在它调用自身时递增。

private string ExpandoToString(object propVal, string propName, int indent = 0)
{

    ...

    // Append this object type.
    sb.Append(Indent(indent) + UppercaseFirst(propName) + " " + propName + " consists of..." + Environment.NewLine);

    ...

    sb.Append(ExpandoToString(propVal, propName, indent + 1) ...);