在 c# 中动态创建 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;

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

jsonObj={FirstName="Json0", LastName="Json1"};
[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}
    }
}

我找到了一个与DPeden非常相似的解决方案,尽管不需要使用IDictionary,但您可以直接从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 }

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

使用 dynamicJObject

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

分配属性的另一种方法:

var obj = new JObject();
obj["ProductName"] = "Elbow Grease";
obj["Enabled"] = true;
obj["StockCount"] = 9000;

或使用JObject.FromObject

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

相关内容

  • 没有找到相关文章

最新更新