Convert the Generic Collection to JSON in C #

advertisements

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("[email protected]", new { id = 1, first = "FirstName", last = "LastName" });
dict.Add("[email protected]", new { id = 2, first = "FirstName", last = "LastName" });
dict.Add("[email protected]", new { id = 3, first = "FirstName", last = "LastName" });
dict.Add("[email protected]", new { id = 4, first = "FirstName", last = "LastName" });
string dictJson = new JavaScriptSerializer().Serialize(dict);
//json result (requires output)
//{"[email protected]":{"id":1,"first":"FirstName","last":"LastName"},"[email protected]":{"id":2,"first":"FirstName","last":"LastName"},"[email protected]":{"id":3,"first":"FirstName","last":"LastName"},"[email protected]":{"id":4,"first":"FirstName","last":"LastName"}}

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

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

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

{"[email protected]":{"id":1,"first":"FirstName","last":"LastName"}}


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