在C#中动态创建Json

yqkkidmi  于 2023-05-30  发布在  C#
关注(0)|答案(4)|浏览(298)

我需要通过循环列来动态创建一个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"};
fd3cxomn

fd3cxomn1#

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

ttygqcqt2#

我发现了一个非常类似于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 }
ru9i0ody

ru9i0ody3#

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

cedebl8k4#

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

相关问题