在c#中动态创建Json

时间:2012-04-20 19:53:25

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

我需要通过循环遍历列来动态创建Json对象。 所以声明一个空的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;

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

4 个答案:

答案 0 :(得分:27)

[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}
    }
}

答案 1 :(得分:16)

您应该使用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"}

答案 2 :(得分:12)

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

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

,输出变为:

{"Bar":"something","Test":true}

答案 3 :(得分:3)

使用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