gpt4 book ai didi

C# JSON 将字典序列化为 {key :value, ...} 而不是 {key :key, value :value, ...}

转载 作者:IT老高 更新时间:2023-10-28 12:44:22 25 4
gpt4 key购买 nike

是否可以使用 DataContractJsonSerializer 将 .Net Dictionary 序列化为 JSON,其格式为:

{
key0:value0,
key1:value1,
...
}

我使用字典 ,因为没有预定义的输入结构。

我对 DataContractJsonSerializer 结果很感兴趣!我已经找到了一个“Surrogate”的例子,但是输出中有一个额外的“数据”,如果字典 是,转义也是假的。


我找到了解决方案,多么需要!首先,一个可序列化的“字典”类:(当然,这个示例只以一种方式工作,但我不需要反序列化)

[Serializable]
public class MyJsonDictionary<K, V> : ISerializable {
Dictionary<K, V> dict = new Dictionary<K, V>();

public MyJsonDictionary() { }

protected MyJsonDictionary( SerializationInfo info, StreamingContext context ) {
throw new NotImplementedException();
}

public void GetObjectData( SerializationInfo info, StreamingContext context ) {
foreach( K key in dict.Keys ) {
info.AddValue( key.ToString(), dict[ key ] );
}
}

public void Add( K key, V value ) {
dict.Add( key, value );
}

public V this[ K index ] {
set { dict[ index ] = value; }
get { return dict[ index ]; }
}
}

用法:

public class MainClass {
public static String Serialize( Object data ) {
var serializer = new DataContractJsonSerializer( data.GetType() );
var ms = new MemoryStream();
serializer.WriteObject( ms, data );

return Encoding.UTF8.GetString( ms.ToArray() );
}

public static void Main() {
MyJsonDictionary<String, Object> result = new MyJsonDictionary<String, Object>();
result["foo"] = "bar";
result["Name"] = "John Doe";
result["Age"] = 32;
MyJsonDictionary<String, Object> address = new MyJsonDictionary<String, Object>();
result["Address"] = address;
address["Street"] = "30 Rockefeller Plaza";
address["City"] = "New York City";
address["State"] = "NY";

Console.WriteLine( Serialize( result ) );

Console.ReadLine();
}
}

结果:

{
"foo":"bar",
"Name":"John Doe",
"Age":32,
"Address":{
"__type":"MyJsonDictionaryOfstringanyType:#Json_Dictionary_Test",
"Street":"30 Rockefeller Plaza",
"City":"New York City",
"State":"NY"
}
}

最佳答案

Json.NET 会这样做...

Dictionary<string, string> values = new Dictionary<string, string>();
values.Add("key1", "value1");
values.Add("key2", "value2");

string json = JsonConvert.SerializeObject(values);
// {
// "key1": "value1",
// "key2": "value2"
// }

更多示例: Serializing Collections with Json.NET

关于C# JSON 将字典序列化为 {key :value, ...} 而不是 {key :key, value :value, ...},我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4861138/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com