简体   繁体   English

根据C#中未知的JSON内容创建无序列表

[英]Create an unordered list from unknown JSON content in C#

I am looking to create a treeview style field selector similar to http://json.parser.online.fr/ . 我正在寻找创建类似于http://json.parser.online.fr/的树视图样式字段选择器。

The idea being that the user can select which fields they want to use from an unknown source of JSON content. 这样的想法是,用户可以从未知的JSON内容源中选择他们要使用的字段。

I want to create an output similar to http://mind2soft.com/labs/jquery/tree/ but creating the content in C# 我想创建类似于http://mind2soft.com/labs/jquery/tree/的输出,但是要在C#中创建内容

I have the following code 我有以下代码

JsonTextReader reader = new JsonTextReader(new StringReader(jsoncontent));
string output = @"<ul id='tree'>
                <li><a href='#'>Data Preview</a>
                <ul>";
while (reader.Read()) {
    if (reader.Value != null) {
        if (reader.TokenType == JsonToken.PropertyName) {
            output += "<li><a href=''>" + reader.Value.ToString() + "</a></li>";
        }

    } else {
        if (reader.TokenType == JsonToken.StartArray) {
            output += "<ul><li>";
        }
        if (reader.TokenType == JsonToken.EndArray) {
            output += "</li></ul>";
        }
        if (reader.TokenType == JsonToken.StartObject) {
            output += "<ul>";
        }
        if (reader.TokenType == JsonToken.EndObject) {
            output += "</ul>";
        }
    }
}

output += @"</ul>
            </li>
            </ul>";

However my desired output is creating multiple of 'UL' tags as I am starting arrays and objects at the same time. 但是,当我同时启动数组和对象时,我想要的输出是创建多个“ UL”标签。

Can anyone please guide me in the right direction. 谁能指导我正确的方向。

Thanks 谢谢

Replace the if inside the else condition with if else statements 更换if里面的else与条件if else语句

if (reader.TokenType == JsonToken.StartArray) {
    output += "<ul><li>";
}
else if (reader.TokenType == JsonToken.EndArray) {
    output += "</li></ul>";
}
else if (reader.TokenType == JsonToken.StartObject) {
    output += "<ul>";
}
else if (reader.TokenType == JsonToken.EndObject) {
    output += "</ul>";
}

Looks like multiple conditions are being satisfied on each iteration 看起来每次迭代都满足多个条件

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM