Aaa*_*aaa 61 c# serialization json dictionary
是否可以使用以下格式的DataContractJsonSerializer将.Net Dictionary <Key,Value>序列化为JSON :
{
key0:value0,
key1:value1,
...
}
Run Code Online (Sandbox Code Playgroud)
我使用Dictionary <K,V>,因为没有预定义的输入结构.
我对DataContractJsonSerializer结果感兴趣!我已经找到了一个"Surrogate"示例,但输出中还有一个"数据",如果字典<K,String>,则转义也是假的.
我找到了解决方案,需要什么!首先,一个可序列化的"字典"类:(当然,这个示例只是以一种方式工作,但我不需要反序列化)
[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 ]; }
}
}
Run Code Online (Sandbox Code Playgroud)
用法:
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();
}
}
Run Code Online (Sandbox Code Playgroud)
结果如下:
{
"foo":"bar",
"Name":"John Doe",
"Age":32,
"Address":{
"__type":"MyJsonDictionaryOfstringanyType:#Json_Dictionary_Test",
"Street":"30 Rockefeller Plaza",
"City":"New York City",
"State":"NY"
}
}
Run Code Online (Sandbox Code Playgroud)
Jam*_*ing 54
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"
// }
Run Code Online (Sandbox Code Playgroud)
更多示例:使用Json.NET序列化集合
Mar*_*cka 23
在.NET 5及更高版本中,您可以简单地编写:
using System;
using System.Collections.Generic;
public class Program
{
public static void Main()
{
Dictionary<string, string> values = new();
values.Add("key1", "value1");
values.Add("key2", "value2");
string json = System.Text.Json.JsonSerializer.Serialize(values);
Console.WriteLine(json);
}
}
Run Code Online (Sandbox Code Playgroud)
要得到{"key1":"value1","key2":"value2"}。
不需要外部依赖。
Maz*_*eri 13
使用属性UseSimpleDictionaryFormat上DataContractJsonSerializer并将其设置为true.
工作:)
我正在使用带有此代码的开箱即用的 MVC4(注意里面的两个参数ToDictionary)
var result = new JsonResult()
{
Data = new
{
partials = GetPartials(data.Partials).ToDictionary(x => x.Key, y=> y.Value)
}
};
Run Code Online (Sandbox Code Playgroud)
我得到了预期的结果:
{"partials":{"cartSummary":"\u003cb\u003eCART SUMMARY\u003c/b\u003e"}}
Run Code Online (Sandbox Code Playgroud)
重要提示:MVC4 中的 WebAPI 使用开箱即用的 JSON.NET 序列化,但标准 WebJsonResult操作结果没有。因此我建议使用自定义 ActionResult 来强制 JSON.NET 序列化。你也可以得到很好的格式
这是一个简单的操作结果 JsonNetResult
http://james.newtonking.com/archive/2008/10/16/asp-net-mvc-and-json-net.aspx
在序列化日期时,您会看到不同之处(并且可以确保您使用的是正确的):
微软方式:
{"wireTime":"\/Date(1355627201572)\/"}
Run Code Online (Sandbox Code Playgroud)
JSON.NET 方式:
{"wireTime":"2012-12-15T19:07:03.5247384-08:00"}
Run Code Online (Sandbox Code Playgroud)
不幸的是,目前在最新版本的 DataContractJsonSerializer 中这是不可能的。请参阅:http ://connect.microsoft.com/VisualStudio/feedback/details/558686/datacontractjsonserializer-should-serialize-dictionary-kv-as-a-json-associative-array
当前建议的解决方法是使用 JavaScriptSerializer,如上面 Mark 建议的那样。
祝你好运!