我正在寻找一种方法来获得这个
{
"parameters": {
"object1": {
"propertie1": "value",
"propertie2": "value"
},
"object2": {
"propertie1": "value",
"propertie2": "value"
}
}
}
C# 我得到了这样的对象
public class MyObject
{
public Dictionnary<string, List < KeyValuePai < string, object > > > parameters = new Dictionnary<string, List < KeyValuePai < string, object > > >();
}
我在此字典中添加了这样的数据:
MyObject.AddParameters("object1", new List < KeyValuePair < string, object > > {
new KeyValuePair < String, object >("propertie1", "value"),
new KeyValuePair < String, object >("propertie2", "value"),
}
MyObject.AddParameters("object2", new List < KeyValuePair < string, object > > {
new KeyValuePair < String, object >("propertie1", "value"),
new KeyValuePair < String, object >("propertie2", "value"),
}
当我在 php 中解码我的序列化对象时,我得到:
{
"parameters": {
"object1": [
{
"Key": "propertie1",
"Value": "value"
},
{
"Key": "propertie2",
"Value": "value"
}
],
"object2": [
{
"Key": "propertie1",
"Value": "value"
},
{
"Key": "propertie2",
"Value": "value"
}
]
},
}
如何从 JSON.Net 序列化中获得正确的格式?
所需的形式在 C# 中添加数据。
您现在添加数据的方式确实会转换为该输出。
在 C# 中需要这样的东西:
MyObject.AddParameters("object1", new List < KeyValuePair < string, object > > {
new KeyValuePair < String, object >("propertie1", "value"),
new KeyValuePair < String, object >("propertie2", "value"),
}
MyObject.AddParameters("object2", new List < KeyValuePair < string, object > > {
new KeyValuePair < String, object >("propertie1", "value"),
new KeyValuePair < String, object >("propertie2", "value"),
}
编辑:
更好的方法是让 JsonConvert.Serialize 完成他的工作,但不是将List<KeyValuePair>
设置为参数,而是传递一个对象。
代码现在
public class MyObject
{
public Dictionnary<string, object> parameters = new Dictionnary<string,object>();
}
并像这样将数据添加到参数表中
MyObject.AddParameters("object1", new {
propertie1 ="value",
propertie2 = "value",
});
MyObject.AddParameters("object2", new {
propertie1 ="value",
propertie2 = "value",
});
现在序列化的词典作为预期的格式。
原答案:
用21021655问题得到了它。
需要像回答中所说的那样编写我自己的转换器
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>>);
}
}
并返回此结果[{"one":1},{"two":2},{"three":3}]