在C#中将通用集合转换为JSON

时间:2016-08-12 06:57:13

标签: c# .net json generics

我在将数据添加到集合中时遇到了一个场景。我需要将一些数据添加到集合中,然后以所需的格式转换为json。

问题是我没有得到我所需的json输出,只有字典集合给了我所需的输出但字典不允许重复键,我需要添加重复数据。

我尝试了不同的收藏品,但无法提出要求。

请查看以下代码段,并建议我一个合适的解决方案。

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

我不想要json结果中的密钥名称。我只需要将电子邮件作为关键字和对象作为其价值。 喜欢这个

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

2 个答案:

答案 0 :(得分:2)

首先,使用List<KeyValuePair<string, object>>,因为您需要允许重复。

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

使用JsonConvert进行序列化。

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

并使用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>>);
    }
}

输出:

[
    {"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

答案 1 :(得分:0)

为此,您需要将数据存储在字典列表中。这不是完美的解决方案,但您可以通过这种方式获得所需的输出

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