Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.6k views
in Technique[技术] by (71.8m points)

c# - JSON Serialize List<KeyValuePair<string, object>>

I used a Dictionary in a Web API project, which is serializing like that in JSON:

{"keyname":{objectvalue},"keyname2:"....

Since I have duplicate keys I could't use Dictionary type any more, and instead now I'm using List<KeyValuePair<string,object>>.

But this is serializing that way:

[{"Key":"keyname","Value":"objectvalue"}...

Is there a way to have the List<KeyValuePair> serialize the same way a dictionary does?

Thanks.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

If you use the Newtonsoft Json.NET library you can do the following.

Define a converter to write the list of key/value pairs the way you want:

class MyConverter : JsonConverter
{
    public override void WriteJson(JsonWriter writer, object value, 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);
            writer.WriteValue(item.Value);
            writer.WriteEndObject();
        }
        writer.WriteEndArray();
    }

    public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
    {
        // TODO...
    }

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

Then use the converter:

var keyValuePairs = new List<KeyValuePair<string, object>>
                    {
                        new KeyValuePair<string, object>("one", 1),
                        new KeyValuePair<string, object>("two", 2),
                        new KeyValuePair<string, object>("three", 3)
                    };

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

This generates [{"one":1},{"two":2},{"three":3}]


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...