简体   繁体   English

C# 如何将 json 项目数组添加到 ExpandoObject?

[英]C# How do I add a json array of items to an ExpandoObject?

How do I create prop3 and include the opening ([) and closing (]) braces in the ExpandoObject syntax?如何创建prop3并在ExpandoObject语法中包含开始 ([) 和结束 (]) 大括号?

prop3 is an array so how do I add userId and userName to the ExpandoObject ? prop3是一个数组,那么如何将userIduserName添加到ExpandoObject

{
    "prop1": "value1",
    "prop2": "value2",
    "prop3": [
        "userId",
        "userName"
    ],
}
    
// my ExpandoObject syntax
    
dynamic form = new ExpandoObject();
    
form.prop1 = "value1";
form.prop2 = "value2";
    
// what ExpandoObject syntax do I use to add the the json array now 
// including the [ ] and each single value to the array?

You can use this你可以用这个

form.prop3 = new[] { "userId", "userName" };

First, you will need to initialize the property with dynamic array then you can use the indexes to put values there.首先,您需要使用dynamic数组初始化属性,然后您可以使用索引将值放在那里。 See:看:

dynamic form = new ExpandoObject();
form.prop1 = "value1";
form.prop2 = "value2";
form.prop3 = new dynamic[2]; // initialized with 2 indexes
form.prop3[0] = "userId"; 
form.prop3[1] = "userName";

And this is the response that you get if you generate the Json:这是生成 Json 时得到的响应:

{
  "prop1": "value1",
  "prop2": "value2",
  "prop3": [
    "userId",
    "userName"
  ]
}

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

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