mar*_*amb 21 c# json keyvaluepair
我是JSON的新手,请帮忙!
我试图将a序列List<KeyValuePair<string, string>>化为JSON
目前:
[{"Key":"MyKey 1","Value":"MyValue 1"},{"Key":"MyKey 2","Value":"MyValue 2"}]
Run Code Online (Sandbox Code Playgroud)
预期:
[{"MyKey 1":"MyValue 1"},{"MyKey 2":"MyValue 2"}]
Run Code Online (Sandbox Code Playgroud)
这是我的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;
}
}
Run Code Online (Sandbox Code Playgroud)
我是从这样的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);
Run Code Online (Sandbox Code Playgroud)
Orc*_*usZ 29
您可以使用Newtonsoft和字典:
var dict = new Dictionary<int, string>();
dict.Add(1, "one");
dict.Add(2, "two");
var output = Newtonsoft.Json.JsonConvert.SerializeObject(dict);
Run Code Online (Sandbox Code Playgroud)
输出是:
{"1":"one","2":"two"}
Run Code Online (Sandbox Code Playgroud)
编辑
感谢 @Sergey Berezovskiy提供的信息.
您目前正在使用Newtonsoft,因此只需将您更改List<KeyValuePair<object, object>>为Dictionary<object,object>并使用包中的serialize和deserialize方法.
所以我不想使用除本机 c# 之外的任何东西来解决类似的问题,作为参考,这是使用 .net 4、jquery 3.2.1 和主干 1.2.0。
我的问题是List<KeyValuePair<...>>控制器会处理到主干模型中,但是当我保存该模型时,控制器无法绑定列表。
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);
}
Run Code Online (Sandbox Code Playgroud)
网络捕获:
"SomeList":[{"Key":13,"Value":"aaab"},{"Key":248,"Value":"aaac"}]
Run Code Online (Sandbox Code Playgroud)
但是,即使在支持 model.js 中正确设置 SomeList 尝试保存模型而不对其进行任何更改,也会导致绑定 SomeModel 对象与请求正文中的参数具有相同的长度,但所有键和值都为空:
[HttpPut]
SomeControllerMethod([FromBody] SomeModel){
SomeModel.SomeList; // Count = 2, all keys and values null.
}
Run Code Online (Sandbox Code Playgroud)
我唯一能找到的是 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;
}
}
Run Code Online (Sandbox Code Playgroud)设置您的绑定类模型以接受您的自定义包装器对象。
public class SomeModel
{
public List<KeyValuePairWrapper> KeyValuePairList{ get; set };
}
Run Code Online (Sandbox Code Playgroud)从控制器中获取一些 json 数据
[HttpGet]
SomeControllerMethod() {
SomeModel someModel = new SomeModel();
someModel.KeyValuePairList = GetListSortedAlphabetically();
return this.Json(someModel, JsonBehavior.AllowGet);
}
Run Code Online (Sandbox Code Playgroud)稍后做一些事情,也许调用了model.save(null, ...)
[HttpPut]
SomeControllerMethod([FromBody] SomeModel){
SomeModel.KeyValuePairList ; // Count = 2, all keys and values are correct.
}
Run Code Online (Sandbox Code Playgroud)| 归档时间: |
|
| 查看次数: |
30849 次 |
| 最近记录: |