41

我需要通过循环遍历列来动态创建一个 Json 对象。所以声明一个空的 json 对象然后动态地向它添加元素。

例如:

List<String> columns = new List<String>{"FirstName","LastName"};

var jsonObj = new {};

for(Int32 i=0;i<columns.Count();i++)
    jsonObj[col[i]]="Json" + i;

最终的 json 对象应该是这样的:

jsonObj={FirstName="Json0", LastName="Json1"};
4

4 回答 4

55
[TestFixture]
public class DynamicJson
{
    [Test]
    public void Test()
    {
        dynamic flexible = new ExpandoObject();
        flexible.Int = 3;
        flexible.String = "hi";

        var dictionary = (IDictionary<string, object>)flexible;
        dictionary.Add("Bool", false);

        var serialized = JsonConvert.SerializeObject(dictionary); // {"Int":3,"String":"hi","Bool":false}
    }
}
于 2012-04-20T20:21:22.820 回答
19

我找到了一个与 DPeden 非常相似的解决方案,虽然不需要使用 IDictionary,但您可以直接从 an 传递ExpandoObject到 JSON 转换:

dynamic foo = new ExpandoObject();
foo.Bar = "something";
foo.Test = true;
string json = Newtonsoft.Json.JsonConvert.SerializeObject(foo);

输出变为:

{ "FirstName":"John", "LastName":"Doe", "Active":true }
于 2014-05-07T19:04:37.430 回答
18

你应该使用JavaScriptSerializer. 这可以为您将实际类型序列化为 JSON :)

参考:http: //msdn.microsoft.com/en-us/library/system.web.script.serialization.javascriptserializer.aspx

编辑:像这样的东西?

var columns = new Dictionary<string, string>
            {
                { "FirstName", "Mathew"},
                { "Surname", "Thompson"},
                { "Gender", "Male"},
                { "SerializeMe", "GoOnThen"}
            };

var jsSerializer = new JavaScriptSerializer();

var serialized = jsSerializer.Serialize(columns);

输出:

{"FirstName":"Mathew","Surname":"Thompson","Gender":"Male","SerializeMe":"GoOnThen"}
于 2012-04-20T19:55:44.843 回答
5

使用dynamicJObject

dynamic product = new JObject();
product.ProductName = "Elbow Grease";
product.Enabled = true;
product.StockCount = 9000;

Console.WriteLine(product.ToString());
// {
//   "ProductName": "Elbow Grease",
//   "Enabled": true,
//   "StockCount": 9000
// }

或者怎么样:

JObject obj = JObject.FromObject(new
{
    ProductName = "Elbow Grease",
    Enabled = true,
    StockCount = 9000
});

Console.WriteLine(obj.ToString());
// {
//   "ProductName": "Elbow Grease",
//   "Enabled": true,
//   "StockCount": 9000
// }

https://www.newtonsoft.com/json/help/html/CreateJsonDynamic.htm

于 2020-01-16T15:48:42.023 回答