Create Json dynamically in c#

柔情痞子 提交于 2020-12-24 05:09:21

问题


I need to create a Json object dynamically by looping through columns. so declaring an empty json object then add elements to it dynamically.

eg:

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

var jsonObj = new {};

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

And the final json object should be like this:

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

回答1:


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



回答2:


You should use the JavaScriptSerializer. That can Serialize actual types for you into JSON :)

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

EDIT: Something like this?

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

var jsSerializer = new JavaScriptSerializer();

var serialized = jsSerializer.Serialize(columns);

Output:

{"FirstName":"Mathew","Surname":"Thompson","Gender":"Male","SerializeMe":"GoOnThen"}



回答3:


I found a solution very similar to DPeden, though there is no need to use the IDictionary, you can pass directly from an ExpandoObject to a JSON convert:

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

and the output becomes:

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



回答4:


Using dynamic and JObject

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

Or how about:

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



来源:https://stackoverflow.com/questions/10252675/create-json-dynamically-in-c-sharp

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!