3

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"}}
Gilad Green
  • 36,708
  • 7
  • 61
  • 95

2 Answers2

2

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

Community
  • 1
  • 1
smoksnes
  • 10,509
  • 4
  • 49
  • 74
1

In order to that you need to store your data in list of dictionary. It is not perfect solution but you can get your desired output in this way

class ValueHolder {
public string id { get; set; }
public string otherProp { get; set; }
}


var dic1 = new Dictionary<string, ValueHolder>();
dic1.Add("b@b.com", new ValueHolder { id = "1", otherProp = "Lorem" });
dic1.Add("a@a.com", new ValueHolder { id = "1", otherProp = "Lorem" });

var dic2 = new Dictionary<string, ValueHolder>();
dic2.Add("b@b.com", new ValueHolder { id = "2", otherProp = "Lorem" });
dic2.Add("a@a.com", new ValueHolder { id = "2", otherProp = "Lorem" });

var listOfDic = new List<Dictionary<string, ValueHolder>> { dic1, dic2 };
var result = JsonConvert.SerializeObject(listOfDic, Formatting.Indented);
[
  {
    "b@b.com": {
      "id": "1",
      "otherProp": "lorem"
    },
    "a@a.com": {
      "id": "1",
      "otherProp": "lorem"
    }
  },
  {
    "b@b.com": {
      "id": "2",
      "otherProp": "lorem"
    },
    "a@a.com": {
      "id": "2",
      "otherProp": "lorem"
    }
  }
]
omer faruk
  • 350
  • 4
  • 13