我怎样才能在c#

时间:2017-08-17 03:28:53

标签: c# arrays json json.net

我希望使用c#从JSON中获取“水果”,“动物”,“数字”,并且我希望获得“水果”,“动物”和“数字”中的值我正在使用json.net但我无法弄清楚如何获得我想要的数据。

{
   "fruits":[
      "apple",
      "orange",
      "grapes",
      "banana"
   ],
   "animals":[
      "cat",
      "dog",
      "lion",
      "bird",
      "horse" 
   ],
 "numbers":[
      "1",
      "2",
      "3",
      "4",
      "5" 
   ]
}

我知道我可以通过这个实现这个目标

public class RootObject
{
    public List<string> fruits { get; set; }
    public List<string> animals { get; set; }
    public List<string> numbers { get; set; }
}

但是当我添加另一个像颜色的对象时,我需要添加

public List<string> colors{ get; set; }

我想要的只是简单地获取对象名称及其值而无需定义新属性。

我知道这已经得到了回答,如果有的话请点评一些链接。

2 个答案:

答案 0 :(得分:1)

您可以为您的类型使用通用字典,并使用Newtonsoft JSON库进行反序列化。假设您的JSON示例位于文件C:\ temp \ json.txt:

// User ID label
let userIDLabel:UILabel = UILabel()
userIDLabel.backgroundColor = UIColor.gray
userIDLabel.text = "User ID"

// Password label
let passwordLabel:UILabel = UILabel()
passwordLabel.backgroundColor = UIColor.gray
passwordLabel.text = "Password"

// User ID text
let userIDText:UITextField = UITextField()
userIDText.backgroundColor = UIColor.blue

// Password text
let passwordText:UITextField = UITextField()
passwordText.backgroundColor = UIColor.blue

// Login button
let loginBtn:UIButton = UIButton()
loginBtn.backgroundColor = UIColor.gray
loginBtn.setTitle("Login", for: .normal)

// Container view
let container:UIStackView = UIStackView()
container.translatesAutoresizingMaskIntoConstraints = false
container.axis = .vertical

container.addArrangedSubview(userIDLabel)
container.addArrangedSubview(userIDText)
container.addArrangedSubview(passwordLabel)
container.addArrangedSubview(passwordText)
container.addArrangedSubview(loginBtn)

view.addSubview(container)

// Add constraints
let centerXConstraint = NSLayoutConstraint(item: container, attribute: .centerX, relatedBy: .equal, toItem: view, attribute: .centerX, multiplier: 1, constant: 0)
let centerYConstraint = NSLayoutConstraint(item: container, attribute: .centerY, relatedBy: .equal, toItem: view, attribute: .centerY, multiplier: 1, constant: 0)

view.addConstraint(centerXConstraint)
view.addConstraint(centerYConstraint)

然后你可以从词典中获得你的水果或颜色或其他任何东西。

答案 1 :(得分:0)

你是对的,你在解析给定的JSON时不能使用类,因为你的JSON数据没有固定而且与特定项目无关,这就是为什么它的原因在字典中可以使用dynamic对象的位置。 以下示例演示了如何使其工作。我已经增加了2件物品,比如汽车和笔记本电脑

string json = "{'fruits':['apple','orange','grapes','banana']," +
                      "'animals':['cat','dog','lion','bird','horse' ]," +
                      "'cars':['bmw','mustang','suzuki']," +
                      "'laptops':['hp','acer','samsung','microsoft','mac' ]," +
                      "'numbers':['1','2','3','4','5' ]}";
        var dict = JsonConvert.DeserializeObject<Dictionary<string, dynamic>>(json);
        foreach (var item in dict)
        {
            var objName = item.Key;
            var items = item.Value;
        }

以下是上述代码的执行。希望它有所帮助。

Code Execution