【问题标题】:Parse Json using Json Net and C# to fill a dropdown使用 Json Net 和 C# 解析 Json 以填充下拉列表
【发布时间】:2014-02-15 02:28:50
【问题描述】:

我有一个类似下面的 Json: [{“示例温度”:“值”},{“示例默认”:“”,“选定”:真}]

我需要填写一个下拉列表,例如: 下拉列表应包含值:示例 temp 默认示例

Example Default 应该是默认选择的值,

我试过下面的代码:

JArray jArray = JArray.Parse(jsonstring);

foreach (JObject jObject in jArray.Children<JObject>())
{
   foreach (JProperty jProperty in jObject.Properties())
    {
     string name = jProperty.Name.Trim();
      string value = jProperty.Value.ToString().Trim();
        drpValues.Items.Add(new RadComboBoxItem(name, value));
     }
 }

但“选定”也以下拉值的形式出现。

非常感谢任何帮助。

非常感谢!

-PT

【问题讨论】:

  • 你能改变你的json格式吗?如果您可以将其更改为 [{"Text" : "Example temp", "Value" : "SomeValue"}, {"Text" : "Example Default", "Value" : "", "selected": true}] 之类的内容会更容易
  • 感谢您的回复 ekad!如何用这个 json 填充下拉列表,请帮忙!我将此 json 与我的下拉填充逻辑一起使用,现在我将下拉值作为示例 temp、Value、Text、Value

标签: c# asp.net json json.net


【解决方案1】:

假设只有一个默认值,这段代码应该可以工作

JArray jArray = JArray.Parse(jsonStr);

bool isDefault;
string defaultValue;
foreach (JObject jObject in jArray.Children<JObject>())
{
    isDefault = false;

    // check if current jObject contains a property named "selected"
    // and if the value is true
    JProperty p = jObject.Properties().SingleOrDefault(x => x.Name == "selected");
    if (p != null && (bool)p.Value == true)
    {
        isDefault = true;
    }

    foreach (JProperty jProperty in jObject.Properties())
    {
        string name = jProperty.Name.Trim();
        string value = jProperty.Value.ToString().Trim();

        if (name != "selected")
        {
            drpValues.Items.Add(new RadComboBoxItem(name, value));
            if (isDefault)
            {
                defaultValue = value;
            }
        }
    }
}

// set the dropdown selected item
RadComboBoxItem itemToSelect = drpValues.FindItemByValue(defaultValue);
itemToSelect.Selected = true;

【讨论】:

  • 这看起来很棒!在不更改Json的情况下寻找任何答案,希望为用户减少Json以便于更新和减少混乱,非常感谢您的回复。
  • 可以在不改变Json的情况下做到这一点吗?谢谢!
  • 查看编辑后的答案,我想这就是你要找的。​​span>
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-08-13
  • 1970-01-01
  • 2013-04-16
  • 2021-04-04
  • 1970-01-01
相关资源
最近更新 更多