序列化列表<keyvaluepair <string,string =“”>&gt;作为JSON

时间:2017-01-06 09:51:55

标签: c# json keyvaluepair

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

我提到了thisthis的一些例子。

这是我的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);

2 个答案:

答案 0 :(得分:23)

您可以使用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>,然后使用该软件包中的序列化和反序列化方法。

答案 1 :(得分:2)

所以我不想使用除了本地c#之外的任何东西来解决类似问题,并且参考这是使用.net 4,jquery 3.2.1和骨干1.2.0。

我的问题是List<KeyValuePair<...>>会从控制器进入骨干模型,但是当我保存该模型时,控制器无法绑定List。

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.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;
        }
    }
    
  • 设置绑定类模型以接受自定义包装器对象。

    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.
    }