将列表 <KeyValuePair<string, string>> 序列化为 JSON

Serialize List<KeyValuePair<string, string>> as JSON

我是 JSON 的新手,请帮忙!

我正在尝试将 List<KeyValuePair<string, string>> 序列化为 JSON

目前:

[{"Key":"MyKey 1","Value":"MyValue 1"},{"Key":"MyKey 2","Value":"MyValue 2"}]

预计:

[{"MyKey 1":"MyValue 1"},{"MyKey 2":"MyValue 2"}]

我参考了 this and this 中的一些示例。

这是我的 KeyValuePairJsonConverter : JsonConverter

public class KeyValuePairJsonConverter : JsonConverter
{
    public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
    {
        List<KeyValuePair<object, object>> list = value as List<KeyValuePair<object, object>>;
        writer.WriteStartArray();
        foreach (var item in list)
        {
            writer.WriteStartObject();
            writer.WritePropertyName(item.Key.ToString());
            writer.WriteValue(item.Value.ToString());
            writer.WriteEndObject();
        }
        writer.WriteEndArray();
    }

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

    public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
    {
        var jsonObject = JObject.Load(reader);
        var target = Create(objectType, jsonObject);
        serializer.Populate(jsonObject.CreateReader(), target);
        return target;
    }

    private object Create(Type objectType, JObject jsonObject)
    {
        if (FieldExists("Key", jsonObject))
        {
            return jsonObject["Key"].ToString();
        }

        if (FieldExists("Value", jsonObject))
        {
            return jsonObject["Value"].ToString();
        }
        return null;
    }

    private bool FieldExists(string fieldName, JObject jsonObject)
    {
        return jsonObject[fieldName] != null;
    }
}

我是从这样的 WebService 方法调用它的

List<KeyValuePair<string, string>> valuesList = new List<KeyValuePair<string, string>>();
Dictionary<string, string> valuesDict = SomeDictionaryMethod();

foreach(KeyValuePair<string, string> keyValue in valuesDict)
{
    valuesList.Add(keyValue);
}

JsonSerializerSettings jsonSettings = new JsonSerializerSettings { Converters = new [] {new KeyValuePairJsonConverter()} };
string valuesJson = JsonConvert.SerializeObject(valuesList, jsonSettings);

您可以使用 Newtonsoft 和词典:

    var dict = new Dictionary<int, string>();
    dict.Add(1, "one");
    dict.Add(2, "two");

    var output = Newtonsoft.Json.JsonConvert.SerializeObject(dict);

输出是:

{"1":"one","2":"two"}

编辑

感谢 @Sergey Berezovskiy 提供的信息。

您目前正在使用 Newtonsoft,因此只需将 List<KeyValuePair<object, object>> 更改为 Dictionary<object,object> 并使用包中的序列化和反序列化方法。

所以我不想使用本机 c# 来解决类似问题,作为参考,这是使用 .net 4、jquery 3.2.1 和 backbone 1.2.0。

我的问题是 List<KeyValuePair<...>> 会在控制器外处理成 backbone 模型,但是当我保存该模型时,控制器无法绑定列表。

public class SomeModel {
    List<KeyValuePair<int, String>> SomeList { get; set; }
}

[HttpGet]
SomeControllerMethod() {
    SomeModel someModel = new SomeModel();
    someModel.SomeList = GetListSortedAlphabetically();
    return this.Json(someModel, JsonBehavior.AllowGet);
}

网络捕获:

"SomeList":[{"Key":13,"Value":"aaab"},{"Key":248,"Value":"aaac"}]

但是即使这在支持中正确设置了 SomeList model.js 尝试保存模型而不对其进行任何更改会导致绑定 SomeModel 对象与请求正文中的参数具有相同的长度,但所有键和值均为空:

[HttpPut]
SomeControllerMethod([FromBody] SomeModel){
    SomeModel.SomeList; // Count = 2, all keys and values null.
}

我唯一能找到的是 KeyValuePair 是一个结构,而不是可以用这种方式实例化的东西。我最终做的是以下内容:

  • 在包含键、值字段的某处添加模型包装器:

    public class KeyValuePairWrapper {
        public int Key { get; set; }
        public String Value { get; set; }
    
        //default constructor will be required for binding, the Web.MVC binder will invoke this and set the Key and Value accordingly.
        public KeyValuePairWrapper() { }
    
        //a convenience method which allows you to set the values while sorting
        public KeyValuePairWrapper(int key, String value)
        {
            Key = key;
            Value = value;
        }
    }
    
  • 设置绑定 class 模型以接受自定义包装器对象。

    public class SomeModel
    {
        public List<KeyValuePairWrapper> KeyValuePairList{ get; set }; 
    }
    
  • 从控制器中获取一些 json 数据

    [HttpGet]
    SomeControllerMethod() {
        SomeModel someModel = new SomeModel();
        someModel.KeyValuePairList = GetListSortedAlphabetically();
        return this.Json(someModel, JsonBehavior.AllowGet);
    }
    
  • 稍后再做一些事情,可能会调用 model.save(null, ...)

    [HttpPut]
    SomeControllerMethod([FromBody] SomeModel){
        SomeModel.KeyValuePairList ; // Count = 2, all keys and values are correct.
    }