提问者:小点点

在C#中如何根据模型数动态构造JSON键名?


例如:

{
   "Books": [
       {
           "Name-1":"The Alchemist",
           "Type-1":"Fiction"
       },
       {
           "Name-2":"Silent Spring",
           "Type-2":"Non-Fiction"
       },
       {
           "Name-3":"1984",
           "Type-3":"Fiction"
       }
   ]
}

我用属性“name”和“type”定义了Books模型。如何从Books Collection中创建如上所示的JSON?


共2个答案

匿名用户

您需要通过JsonTextWriter生成json

        StringBuilder sb = new StringBuilder();
        StringWriter sw = new StringWriter(sb);
        using (JsonWriter writer = new JsonTextWriter(sw))
        {
            writer.WriteStartObject();

            writer.WritePropertyName("Books");

            writer.WriteStartArray();

            //your for


            writer.WriteEndArray();

            writer.WriteEndObject();
        }

类似问题

匿名用户

将书籍映射到字典<;字符串,字符串>;并将其序列化。类似于:

    serializer.Serialize(new { Books = books.Select((x, i) => 
        new Dictionary<string, string> { 
            { $"{nameof(x.Name}-{i+1}", x.Name }, 
            { $"{nameof(x.Type}-{i+1}", x.Type }
        }});

However, it looks very WIERD to have such a Json (I mean with indexes as property names of objects in same array)