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

时间:2015-03-13 19:03:49

标签: c# json json.net

我目前正在开发一个程序,该程序接受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"}}

1 个答案:

答案 0 :(得分:1)

您应该将当前缩进作为参数提供给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) ...);