Abdul Mueed Chaudhry Abdul Mueed Chaudhry - 3 months ago 24
JSON Question

Convert Generic Collection to JSON in C#

I'm facing a scenario while adding data into a collection. I need to add some data into a collection and then convert into json in a required format.

The problem is i'm not getting my required json output, only dictionary collection giving me my required output but dictionary doesn't allow duplicate keys in it, and i need to add duplicate data.

I've tried different collection but unable to get required out put.

Please look at the following code snippets and suggest me a proper solution.

//with distinct emails
var dict = new Dictionary<string, object>();
dict.Add("user1@company.com", new { id = 1, first = "FirstName", last = "LastName" });
dict.Add("user2@company.com", new { id = 2, first = "FirstName", last = "LastName" });
dict.Add("user3@company.com", new { id = 3, first = "FirstName", last = "LastName" });
dict.Add("user4@company.com", new { id = 4, first = "FirstName", last = "LastName" });
string dictJson = new JavaScriptSerializer().Serialize(dict);
//json result (requires output)
//{"user1@company.com":{"id":1,"first":"FirstName","last":"LastName"},"user2@company.com":{"id":2,"first":"FirstName","last":"LastName"},"user3@company.com":{"id":3,"first":"FirstName","last":"LastName"},"user4@company.com":{"id":4,"first":"FirstName","last":"LastName"}}

//Snippet - I: with duplicate emails
var list = new List<KeyValuePair<string, object>>();
list.Add(new KeyValuePair<string, object>("user1@company.com", new { id = 1, first = "FirstName", last = "LastName" }));
list.Add(new KeyValuePair<string, object>("user1@company.com", new { id = 2, first = "FirstName", last = "LastName" }));
list.Add(new KeyValuePair<string, object>("user2@company.com", new { id = 3, first = "FirstName", last = "LastName" }));
list.Add(new KeyValuePair<string, object>("user2@company.com", new { id = 4, first = "FirstName", last = "LastName" }));
string listJson = new JavaScriptSerializer().Serialize(list);
//json result
//[{"Key":"user1@company.com","Value":{"id":1,"first":"FirstName","last":"LastName"}},{"Key":"user1@company.com","Value":{"id":2,"first":"FirstName","last":"LastName"}},{"Key":"user2@company.com","Value":{"id":3,"first":"FirstName","last":"LastName"}},{"Key":"user2@company.com","Value":{"id":4,"first":"FirstName","last":"LastName"}}]

//Snippet - II: with duplicate emails
var tupleList = new List<Tuple<string, CustomClass>>();
tupleList.Add(Tuple.Create("user1@company.com", new CustomClass { id = 1, first = "FirstName", last = "LastName" }));
tupleList.Add(Tuple.Create("user1@company.com", new CustomClass { id = 2, first = "FirstName", last = "LastName" }));
tupleList.Add(Tuple.Create("user2@company.com", new CustomClass { id = 3, first = "FirstName", last = "LastName" }));
tupleList.Add(Tuple.Create("user2@company.com", new CustomClass { id = 4, first = "FirstName", last = "LastName" }));
string tupleListJson = new JavaScriptSerializer().Serialize(tupleList);
//json result
//[{"Item1":"user1@company.com","Item2":{"id":1,"first":"FirstName","last":"LastName"}},{"Item1":"user1@company.com","Item2":{"id":2,"first":"FirstName","last":"LastName"}},{"Item1":"user2@company.com","Item2":{"id":3,"first":"FirstName","last":"LastName"}},{"Item1":"user2@company.com","Item2":{"id":4,"first":"FirstName","last":"LastName"}}]

//Snippet - III: with duplicate emails
var genericList = new List<MainClass>();
genericList.Add(new MainClass { email = "user1@company.com", details = new CustomClass { id = 1, first = "FirstName", last = "LastName" } });
genericList.Add(new MainClass { email = "user1@company.com", details = new CustomClass { id = 2, first = "FirstName", last = "LastName" } });
genericList.Add(new MainClass { email = "user2@company.com", details = new CustomClass { id = 3, first = "FirstName", last = "LastName" } });
genericList.Add(new MainClass { email = "user2@company.com", details = new CustomClass { id = 4, first = "FirstName", last = "LastName" } });
string genericListJson = new JavaScriptSerializer().Serialize(genericList);
//json result
//[{"email":"user1@company.com","details":{"id":1,"first":"FirstName","last":"LastName"}},{"email":"user1@company.com","details":{"id":2,"first":"FirstName","last":"LastName"}},{"email":"user2@company.com","details":{"id":3,"first":"FirstName","last":"LastName"}},{"email":"user2@company.com","details":{"id":4,"first":"FirstName","last":"LastName"}}]


I dont want key name in json result. I just need email as key and object as its value.
Like this

{"user1@company.com":{"id":1,"first":"FirstName","last":"LastName"}}

Answer

First, use a List<KeyValuePair<string, object>> since you need to allow duplicates.

var list = new List<KeyValuePair<string, object>>();
list.Add(new KeyValuePair<string, object>("foo", new { id = 1, first = "FirstName", last = "LastName" }));
list.Add(new KeyValuePair<string, object>("foo", new { id = 1, first = "FirstName", last = "LastName" }));
list.Add(new KeyValuePair<string, object>("foo", new { id = 1, first = "FirstName", last = "LastName" }));

Serialize with JsonConvert.

JsonSerializerSettings settings = new JsonSerializerSettings { Converters = new[] { new MyConverter() } };
string json = JsonConvert.SerializeObject(list, settings);

And use a custom converter inspired from this answer:

public class MyConverter : JsonConverter
{

    public override void WriteJson(JsonWriter writer, object value, Newtonsoft.Json.JsonSerializer serializer)
    {
        List<KeyValuePair<string, object>> list = value as List<KeyValuePair<string, object>>;
        writer.WriteStartArray();
        foreach (var item in list)
        {
            writer.WriteStartObject();
            writer.WritePropertyName(item.Key);
            // Needed because of the dynamic object.
            var jsonValue = JsonConvert.SerializeObject(item.Value);
            writer.WriteValue(jsonValue);
            writer.WriteEndObject();
        }
        writer.WriteEndArray();
    }

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

    public override bool CanConvert(Type objectType)
    {
        return objectType == typeof(List<KeyValuePair<string, object>>);
    }
}

Output:

[
    {"foo":"{\"id\":1,\"first\":\"FirstName\",\"last\":\"LastName\"}"},
    {"foo":"{\"id\":1,\"first\":\"FirstName\",\"last\":\"LastName\"}"},
    {"foo":"{\"id\":1,\"first\":\"FirstName\",\"last\":\"LastName\"}"}
]

enter image description here

Comments