3

Is there any way to serialize collection of objects to json object properties? I would like to use newtonsoft json.

Let's suppouse I have:

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

After serialization I would like to have:

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

Thanks for any help IT Man

aloisdg
  • 22,270
  • 6
  • 85
  • 105
IT Man
  • 933
  • 3
  • 12
  • 33
  • Possible duplicate of [C# Serializing a Collection of Objects](https://stackoverflow.com/questions/1463548/c-sharp-serializing-a-collection-of-objects) – Fuzzybear Jul 10 '18 at 14:52
  • Check this post out: https://stackoverflow.com/questions/9110724/serializing-a-list-to-json or this one: https://stackoverflow.com/questions/23904752/serializing-a-list-of-object-using-json-net – MaholeycowDev Jul 10 '18 at 14:56
  • 1
    Sure, transform it into a dictionary, then serialize it. –  Jul 10 '18 at 14:59

2 Answers2

1

We use a Dictionary, JsonIgnore (from Newtonsoft.Json) and a camel case converter (from 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);
}

output

{"a":{"prop1":"123"},"b":{"prop1":"456"},"c":{"prop1":"789"}}
aloisdg
  • 22,270
  • 6
  • 85
  • 105
0

You can create custom 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);
    }
}

And use it like:

var str = JsonConvert.SerializeObject(items, new ListOfItemsConverter());
Alex Riabov
  • 8,655
  • 5
  • 47
  • 48