将对象列表序列化为对象的属性

时间:2018-07-10 14:48:59

标签: c# json

有什么方法可以将对象集合序列化为json对象属性?我想使用newtonsoft json。

让我支持我吧

class Item
{
    public string Name { get; set; }
    public string Prop1 { get; set; }
}

var items = new List<Item>
{
    new Item { Name = "a", Prop1 = "123" },
    new Item { Name = "b", Prop1 = "456" },
    new Item { Name = "c", Prop1 = "789" }
}

序列化后,我希望拥有:

{
  'a' : { 'prop1': '123' }
  'b' : { 'prop1': '345' }
  'c' : { 'prop1': '789' }
}

感谢您的帮助 IT人

2 个答案:

答案 0 :(得分:1)

我们使用了Dictionary,JsonIgnore(来自Newtonsoft.Json)和骆驼大小写转换器(来自Newtonsoft.Json)

Try it online

public class Item
{
    // jsonignore is an attribute to ... ignore this in json
    [JsonIgnore]
    public string Name { get; set; }
    public string Prop1 { get; set; }
}

public static void Main()
{
    var items = new List<Item>
    {
        new Item { Name = "a", Prop1 = "123" },
        new Item { Name = "b", Prop1 = "456" },
        new Item { Name = "c", Prop1 = "789" }
    };

    // we use a Dictionary as Amy propose in comment
    var obj = items.ToDictionary(x=> x.Name, x => x);
    var json = JsonConvert.SerializeObject(obj, new JsonSerializerSettings 
    { 
        // we need this to use camel case
        ContractResolver = new CamelCasePropertyNamesContractResolver() 
    });

    Console.WriteLine(json);
}

输出

{"a":{"prop1":"123"},"b":{"prop1":"456"},"c":{"prop1":"789"}}

答案 1 :(得分:0)

您可以创建自定义JsonConverter:

class ListOfItemsConverter : JsonConverter
{
    public override bool CanConvert(Type objectType)
    {
        return (objectType == typeof(List<Item>));
    }

    public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
    {
        throw new NotImplementedException();
    }

    public override bool CanWrite
    {
        get { return true; }
    }

    public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
    {
        JObject item = new JObject();

        foreach (var val in (value as List<Item>))
        {
            var internalItem = new JObject {new JProperty("prop1", val.Prop1)};
            item.Add(new JProperty(val.Name, internalItem));
        }

        item.WriteTo(writer);
    }
}

并像这样使用它:

var str = JsonConvert.SerializeObject(items, new ListOfItemsConverter());