我有一个简单的 JSON 键/值列表,通过 POST 发送回 ASP.NET。例子:
{ "key1": "value1", "key2": "value2"}
我不想反序列化为强类型的 .NET 对象
我只需要一个普通的旧字典(字符串,字符串),或一些等效的(哈希表,字典(字符串,对象),老式 StringDictionary——地狱,一个二维字符串数组对我有用。
我可以使用 ASP.NET 3.5 中可用的任何东西,以及流行的 Json.NET(我已经在使用它来对客户端进行序列化)。
显然,这些 JSON 库都没有这种开箱即用的明显能力——它们完全专注于通过强合约进行基于反射的反序列化。
有任何想法吗?
限制:
我不想实现自己的 JSON 解析器 还不能使用 ASP.NET 4.0 宁愿远离旧的、已弃用的 ASP.NET JSON 类
JavaScriptSerizlizer
在 ASP.NET MVC 中使用并且不再被弃用。
Json.NET 这样做...
string json = @"{""key1"":""value1"",""key2"":""value2""}";
var values = JsonConvert.DeserializeObject<Dictionary<string, string>>(json);
更多示例:Serializing Collections with Json.NET
我确实发现 .NET 有一种内置方法可以通过 3.5 System.Web.Extensions
程序集中的 System.Web.Script.Serialization.JavaScriptSerializer
类型将 JSON 字符串转换为 Dictionary<String, Object>
。使用方法DeserializeObject(String)
。
我在将内容类型为“application/json”的 ajax 帖子(通过 jquery)发送到静态 .net 页面方法时偶然发现了这一点,并看到该方法(它有一个类型为 Object
的单个参数)神奇地收到了这个字典。
var jsSerializer = new System.Web.Script.Serialization.JavaScriptSerializer();
后跟 Dictionary<string, object> dict = (Dictionary<string, object>)jsSerializer.DeserializeObject(jsonString);
对于那些在互联网上搜索并偶然发现这篇文章的人,我写了一篇关于如何使用 JavaScriptSerializer 类的博客文章。
阅读更多... http://procbits.com/2011/04/21/quick-json-serializationdeserialization-in-c/
这是一个例子:
var json = "{\"id\":\"13\", \"value\": true}";
var jss = new JavaScriptSerializer();
var table = jss.Deserialize<dynamic>(json);
Console.WriteLine(table["id"]);
Console.WriteLine(table["value"]);
System.Text.Json
现在可以使用 .NET Core 3.0 内置的 System.Text.Json
来完成此操作。现在可以不使用使用第三方库反序列化 JSON。
var json = @"{""key1"":""value1"",""key2"":""value2""}";
var values = JsonSerializer.Deserialize<Dictionary<string, string>>(json);
如果使用 .NET Standard 或 .NET Framework,也可在 NuGet 包 System.Text.Json 中使用。
请务必阅读并理解:
https://github.com/dotnet/runtime/issues/30452
System.Text.Json
是这些天要走的路。
Dictionary<string, JsonElement>
这样您可以使用 childNode.Value.ValueKind == JsonValueKind.Object
测试对象值并使用 JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(childNode.Value);
再次反序列化
我有同样的问题,所以我自己写了这个。该解决方案与其他答案不同,因为它可以反序列化到多个级别。
只需将 JSON 字符串发送到 deserializeToDictionary 函数,它将返回非强类型 Dictionary<string, object>
对象。
旧代码
private Dictionary<string, object> deserializeToDictionary(string jo)
{
var values = JsonConvert.DeserializeObject<Dictionary<string, object>>(jo);
var values2 = new Dictionary<string, object>();
foreach (KeyValuePair<string, object> d in values)
{
// if (d.Value.GetType().FullName.Contains("Newtonsoft.Json.Linq.JObject"))
if (d.Value is JObject)
{
values2.Add(d.Key, deserializeToDictionary(d.Value.ToString()));
}
else
{
values2.Add(d.Key, d.Value);
}
}
return values2;
}
例如:这将返回 Facebook JSON 响应的 Dictionary<string, object>
对象。
测试
private void button1_Click(object sender, EventArgs e)
{
string responsestring = "{\"id\":\"721055828\",\"name\":\"Dasun Sameera Weerasinghe\",\"first_name\":\"Dasun\",\"middle_name\":\"Sameera\",\"last_name\":\"Weerasinghe\",\"username\":\"dasun\",\"gender\":\"male\",\"locale\":\"en_US\", hometown: {id: \"108388329191258\", name: \"Moratuwa, Sri Lanka\",}}";
Dictionary<string, object> values = deserializeToDictionary(responsestring);
}
注意:hometown 进一步反序列化为 Dictionary
更新
如果 JSON 字符串上没有数组,我的旧答案效果很好。如果元素是数组,则此进一步反序列化为 List<object>
。
只需将 JSON 字符串发送到 deserializeToDictionaryOrList 函数,它将返回非强类型 Dictionary<string, object>
对象或 List<object>
时间>。
private static object deserializeToDictionaryOrList(string jo,bool isArray=false)
{
if (!isArray)
{
isArray = jo.Substring(0, 1) == "[";
}
if (!isArray)
{
var values = JsonConvert.DeserializeObject<Dictionary<string, object>>(jo);
var values2 = new Dictionary<string, object>();
foreach (KeyValuePair<string, object> d in values)
{
if (d.Value is JObject)
{
values2.Add(d.Key, deserializeToDictionary(d.Value.ToString()));
}
else if (d.Value is JArray)
{
values2.Add(d.Key, deserializeToDictionary(d.Value.ToString(), true));
}
else
{
values2.Add(d.Key, d.Value);
}
}
return values2;
}else
{
var values = JsonConvert.DeserializeObject<List<object>>(jo);
var values2 = new List<object>();
foreach (var d in values)
{
if (d is JObject)
{
values2.Add(deserializeToDictionary(d.ToString()));
}
else if (d is JArray)
{
values2.Add(deserializeToDictionary(d.ToString(), true));
}
else
{
values2.Add(d);
}
}
return values2;
}
}
is
和 as
运算符对我有很大帮助并简化了我自己的代码。
试图不使用任何外部 JSON 实现,所以我像这样反序列化:
string json = "{\"id\":\"13\", \"value\": true}";
var serializer = new JavaScriptSerializer(); //using System.Web.Script.Serialization;
Dictionary<string, string> values = serializer.Deserialize<Dictionary<string, string>>(json);
System.Web.Script.Serialization
。它只是工作。我什至能够使用像 string json = "{'id':13, 'value': true}";
这样的“无效”JSON。
我只需要解析一个嵌套字典,比如
{
"x": {
"a": 1,
"b": 2,
"c": 3
}
}
JsonConvert.DeserializeObject
没有帮助。我找到了以下方法:
var dict = JObject.Parse(json).SelectToken("x").ToObject<Dictionary<string, int>>();
SelectToken
可让您深入了解所需的字段。您甚至可以指定像 "x.y.z"
这样的路径来进一步深入 JSON 对象。
如果您追求一种轻量级、不添加引用的方法,那么我刚刚编写的这段代码可能会起作用(尽管我不能 100% 保证稳健性)。
using System;
using System.Collections.Generic;
using System.Text;
using System.Text.RegularExpressions;
public Dictionary<string, object> ParseJSON(string json)
{
int end;
return ParseJSON(json, 0, out end);
}
private Dictionary<string, object> ParseJSON(string json, int start, out int end)
{
Dictionary<string, object> dict = new Dictionary<string, object>();
bool escbegin = false;
bool escend = false;
bool inquotes = false;
string key = null;
int cend;
StringBuilder sb = new StringBuilder();
Dictionary<string, object> child = null;
List<object> arraylist = null;
Regex regex = new Regex(@"\\u([0-9a-z]{4})", RegexOptions.IgnoreCase);
int autoKey = 0;
for (int i = start; i < json.Length; i++)
{
char c = json[i];
if (c == '\\') escbegin = !escbegin;
if (!escbegin)
{
if (c == '"')
{
inquotes = !inquotes;
if (!inquotes && arraylist != null)
{
arraylist.Add(DecodeString(regex, sb.ToString()));
sb.Length = 0;
}
continue;
}
if (!inquotes)
{
switch (c)
{
case '{':
if (i != start)
{
child = ParseJSON(json, i, out cend);
if (arraylist != null) arraylist.Add(child);
else
{
dict.Add(key, child);
key = null;
}
i = cend;
}
continue;
case '}':
end = i;
if (key != null)
{
if (arraylist != null) dict.Add(key, arraylist);
else dict.Add(key, DecodeString(regex, sb.ToString()));
}
return dict;
case '[':
arraylist = new List<object>();
continue;
case ']':
if (key == null)
{
key = "array" + autoKey.ToString();
autoKey++;
}
if (arraylist != null && sb.Length > 0)
{
arraylist.Add(sb.ToString());
sb.Length = 0;
}
dict.Add(key, arraylist);
arraylist = null;
key = null;
continue;
case ',':
if (arraylist == null && key != null)
{
dict.Add(key, DecodeString(regex, sb.ToString()));
key = null;
sb.Length = 0;
}
if (arraylist != null && sb.Length > 0)
{
arraylist.Add(sb.ToString());
sb.Length = 0;
}
continue;
case ':':
key = DecodeString(regex, sb.ToString());
sb.Length = 0;
continue;
}
}
}
sb.Append(c);
if (escend) escbegin = false;
if (escbegin) escend = true;
else escend = false;
}
end = json.Length - 1;
return dict; //theoretically shouldn't ever get here
}
private string DecodeString(Regex regex, string str)
{
return Regex.Unescape(regex.Replace(str, match => char.ConvertFromUtf32(Int32.Parse(match.Groups[1].Value, System.Globalization.NumberStyles.HexNumber))));
}
[我意识到这违反了 OP 限制 #1,但从技术上讲,不是你写的,是我写的]
System.RunTime.Serialization
不是其中之一,不幸的是 JSON。 NET 依赖于它,因此它也不能使用。感谢 dexy 的出色工作,我敢于对其进行一些改进,以便能够反序列化数组的数组,see the updated code in my answer here。
Mark Rendle 发布了此 as a comment,我想将其作为答案发布,因为它是迄今为止唯一可以返回成功的解决方案,并且错误代码 json 结果来自 Google reCaptcha 响应。
string jsonReponseString= wClient.DownloadString(requestUrl);
IDictionary<string, object> dict = new JavaScriptSerializer().DeserializeObject(jsonReponseString) as IDictionary<string, object>;
再次感谢,马克!
我在jSnake04和Dasun提交的代码上添加了这里。我添加了代码以从 JArray
实例创建对象列表。它具有双向递归,但由于它在固定的有限树模型上运行,因此除非数据量很大,否则不会出现堆栈溢出的风险。
/// <summary>
/// Deserialize the given JSON string data (<paramref name="data"/>) into a
/// dictionary.
/// </summary>
/// <param name="data">JSON string.</param>
/// <returns>Deserialized dictionary.</returns>
private IDictionary<string, object> DeserializeData(string data)
{
var values = JsonConvert.DeserializeObject<Dictionary<string, object>>(data);
return DeserializeData(values);
}
/// <summary>
/// Deserialize the given JSON object (<paramref name="data"/>) into a dictionary.
/// </summary>
/// <param name="data">JSON object.</param>
/// <returns>Deserialized dictionary.</returns>
private IDictionary<string, object> DeserializeData(JObject data)
{
var dict = data.ToObject<Dictionary<String, Object>>();
return DeserializeData(dict);
}
/// <summary>
/// Deserialize any elements of the given data dictionary (<paramref name="data"/>)
/// that are JSON object or JSON arrays into dictionaries or lists respectively.
/// </summary>
/// <param name="data">Data dictionary.</param>
/// <returns>Deserialized dictionary.</returns>
private IDictionary<string, object> DeserializeData(IDictionary<string, object> data)
{
foreach (var key in data.Keys.ToArray())
{
var value = data[key];
if (value is JObject)
data[key] = DeserializeData(value as JObject);
if (value is JArray)
data[key] = DeserializeData(value as JArray);
}
return data;
}
/// <summary>
/// Deserialize the given JSON array (<paramref name="data"/>) into a list.
/// </summary>
/// <param name="data">Data dictionary.</param>
/// <returns>Deserialized list.</returns>
private IList<Object> DeserializeData(JArray data)
{
var list = data.ToObject<List<Object>>();
for (int i = 0; i < list.Count; i++)
{
var value = list[i];
if (value is JObject)
list[i] = DeserializeData(value as JObject);
if (value is JArray)
list[i] = DeserializeData(value as JArray);
}
return list;
}
对于任何试图将 JSON 转换为字典只是为了从中检索一些值的人。有 a simple way 使用 Newtonsoft.JSON
using Newtonsoft.Json.Linq
...
JObject o = JObject.Parse(@"{
'CPU': 'Intel',
'Drives': [
'DVD read/writer',
'500 gigabyte hard drive'
]
}");
string cpu = (string)o["CPU"];
// Intel
string firstDrive = (string)o["Drives"][0];
// DVD read/writer
IList<string> allDrives = o["Drives"].Select(t => (string)t).ToList();
// DVD read/writer
// 500 gigabyte hard drive
编辑:这可行,但使用 Json.NET 接受的答案要简单得多。如果有人需要纯 BCL 代码,请留下这个。
开箱即用的 .NET 框架不支持它。一个明显的疏忽——并不是每个人都需要反序列化为具有命名属性的对象。所以我最终推出了自己的:
VB.NET:
<Serializable()> Public Class StringStringDictionary
Implements ISerializable
Public dict As System.Collections.Generic.Dictionary(Of String, String)
Public Sub New()
dict = New System.Collections.Generic.Dictionary(Of String, String)
End Sub
Protected Sub New(info As SerializationInfo, _
context As StreamingContext)
dict = New System.Collections.Generic.Dictionary(Of String, String)
For Each entry As SerializationEntry In info
dict.Add(entry.Name, DirectCast(entry.Value, String))
Next
End Sub
Public Sub GetObjectData(info As SerializationInfo, context As StreamingContext) Implements ISerializable.GetObjectData
For Each key As String in dict.Keys
info.AddValue(key, dict.Item(key))
Next
End Sub
End Class
在 C# 上相同:
public class StringStringDictionary : ISerializable
{
public System.Collections.Generic.Dictionary<string, string> dict;
public StringStringDictionary()
{
dict = new System.Collections.Generic.Dictionary<string, string>();
}
protected StringStringDictionary(SerializationInfo info, StreamingContext context)
{
dict = new System.Collections.Generic.Dictionary<string, string>();
foreach (SerializationEntry entry in info)
dict.Add(entry.Name, (string)entry.Value);
}
public void GetObjectData(SerializationInfo info, StreamingContext context)
{
foreach (string key in dict.Keys)
info.AddValue(key, dict[key]);
}
}
调用:
string MyJsonString = "{ \"key1\": \"value1\", \"key2\": \"value2\"}";
System.Runtime.Serialization.Json.DataContractJsonSerializer dcjs = new
System.Runtime.Serialization.Json.DataContractJsonSerializer(
typeof(StringStringDictionary));
System.IO.MemoryStream ms = new
System.IO.MemoryStream(Encoding.UTF8.GetBytes(MyJsonString));
StringStringDictionary myfields = (StringStringDictionary)dcjs.ReadObject(ms);
Response.Write("Value of key2: " + myfields.dict["key2"]);
对不起 C# 和 VB.NET 的混合......
ISerializable
) - 出现异常:"InvalidDataContractException: Type 'StringStringDictionary' cannot be serialized. 考虑用DataContractAttribute 属性,并使用 DataMemberAttribute 属性标记您想要序列化的所有成员。或者,您可以确保该类型是公共的并具有无参数构造函数 - 然后将序列化该类型的所有公共成员,并且不需要任何属性。”
dict
字段已公开,请尝试添加 [DataContract]
&建议的 [DataMember]
- 出现异常:"System.Runtime.Serialization.InvalidDataContractException: ISerializable type 'Translator.Utils.JsonReader+StringStringDictionary' cannot have DataContract." 3)好的,试试 [DataContract]
& [DataMember]
属性(无 ISerializable
继承)- ReadObject
现在完成无异常,但实际上并未解析:myfields.dict == null
我在另一个答案中添加了对 JSON 中的空值的检查
我有同样的问题,所以我自己写了这个。该解决方案与其他答案不同,因为它可以反序列化到多个级别。
只需将 json 字符串发送到 deserializeToDictionary 函数,它将返回非强类型 Dictionary<string, object>
对象。
private Dictionary<string, object> deserializeToDictionary(string jo)
{
var values = JsonConvert.DeserializeObject<Dictionary<string, object>>(jo);
var values2 = new Dictionary<string, object>();
foreach (KeyValuePair<string, object> d in values)
{
if (d.Value != null && d.Value.GetType().FullName.Contains("Newtonsoft.Json.Linq.JObject"))
{
values2.Add(d.Key, deserializeToDictionary(d.Value.ToString()));
}
else
{
values2.Add(d.Key, d.Value);
}
}
return values2;
}
例如:这将返回 Facebook JSON 响应的 Dictionary<string, object>
对象。
private void button1_Click(object sender, EventArgs e)
{
string responsestring = "{\"id\":\"721055828\",\"name\":\"Dasun Sameera
Weerasinghe\",\"first_name\":\"Dasun\",\"middle_name\":\"Sameera\",\"last_name\":\"Weerasinghe\",\"username\":\"dasun\",\"gender\":\"male\",\"locale\":\"en_US\",
hometown: {id: \"108388329191258\", name: \"Moratuwa, Sri Lanka\",}}";
Dictionary<string, object> values = deserializeToDictionary(responsestring);
}
注意:hometown 进一步反序列化为 Dictionary<string, object>
对象。
d.Value is JObject
。您不必通过反射来检查类型。使用 is
运算符,您无需检查是否为空。如果对象为空,则返回 false。
似乎所有这些答案都只是假设您可以从一个更大的对象中获取那个小字符串...系统,这里有一个解决方案:
An answer on gis.stackexchange.com 有 this interesting link。我不得不使用 archive.org 来恢复它,但它提供了一个非常完美的解决方案:一个自定义 IDataContractSurrogate
类,您可以在其中完全实现自己的类型。我能够轻松地扩展它。
不过,我对它进行了很多更改。由于原始资源不再可用,我将在此处发布整个课程:
using System;
using System.CodeDom;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Json;
using System.Text;
namespace JsonTools
{
/// <summary>
/// Allows using Dictionary<String,String> and Dictionary<String,Boolean> types, and any others you'd like to add.
/// Source: https://web.archive.org/web/20100317222656/my6solutions.com/post/2009/06/30/DataContractSerializer-DataContractJsonSerializer-JavaScriptSerializer-XmlSerializer-for-serialization.aspx
/// </summary>
public class JsonSurrogate : IDataContractSurrogate
{
/// <summary>
/// Deserialize an object with added support for the types defined in this class.
/// </summary>
/// <typeparam name="T">Contract class</typeparam>
/// <param name="json">JSON String</param>
/// <param name="encoding">Text encoding</param>
/// <returns>The deserialized object of type T</returns>
public static T Deserialize<T>(String json, Encoding encoding)
{
if (encoding == null)
encoding = new UTF8Encoding(false);
DataContractJsonSerializer deserializer = new DataContractJsonSerializer(
typeof(T), new Type[0], int.MaxValue, true, new JsonSurrogate(), false);
using (MemoryStream stream = new MemoryStream(encoding.GetBytes(json)))
{
T result = (T)deserializer.ReadObject(stream);
return result;
}
}
// make sure all values in this are classes implementing JsonSurrogateObject.
private static Dictionary<Type, Type> KnownTypes =
new Dictionary<Type, Type>()
{
{typeof(Dictionary<String, String>), typeof(SSDictionary)},
{typeof(Dictionary<String, Boolean>), typeof(SBDictionary)}
};
#region Implemented surrogate dictionary classes
[Serializable]
public class SSDictionary : SurrogateDictionary<String>
{
public SSDictionary() : base() {}
protected SSDictionary (SerializationInfo info, StreamingContext context) : base(info, context) {}
}
[Serializable]
public class SBDictionary : SurrogateDictionary<Boolean>
{
public SBDictionary() : base() {}
protected SBDictionary (SerializationInfo info, StreamingContext context) : base(info, context) {}
}
#endregion
/// <summary>Small interface to easily extract the final value from the object.</summary>
public interface JsonSurrogateObject
{
Object DeserializedObject { get; }
}
/// <summary>
/// Class for deserializing any simple dictionary types with a string as key.
/// </summary>
/// <typeparam name="T">Any simple type that will be deserialized correctly.</typeparam>
[Serializable]
public abstract class SurrogateDictionary<T> : ISerializable, JsonSurrogateObject
{
public Object DeserializedObject { get { return dict; } }
private Dictionary<String, T> dict;
public SurrogateDictionary()
{
dict = new Dictionary<String, T>();
}
// deserialize
protected SurrogateDictionary(SerializationInfo info, StreamingContext context)
{
dict = new Dictionary<String, T>();
foreach (SerializationEntry entry in info)
{
// This cast will only work for base types, of course.
dict.Add(entry.Name, (T)entry.Value);
}
}
// serialize
public void GetObjectData(SerializationInfo info, StreamingContext context)
{
foreach (String key in dict.Keys)
{
info.AddValue(key, dict[key]);
}
}
}
/// <summary>
/// Uses the KnownTypes dictionary to get the surrogate classes.
/// </summary>
/// <param name="type"></param>
/// <returns></returns>
public Type GetDataContractType(Type type)
{
Type returnType;
if (KnownTypes.TryGetValue(type, out returnType))
{
return returnType;
}
return type;
}
public object GetObjectToSerialize(object obj, Type targetType)
{
throw new NotImplementedException();
}
/// <summary>
/// Gets the object out of the surrogate datacontract object. This function is the reason all surrogate objects need to implement the JsonSurrogateObject class.
/// </summary>
/// <param name="obj">Result of the deserialization</param>
/// <param name="targetType">Expected target type of the deserialization</param>
/// <returns></returns>
public object GetDeserializedObject(object obj, Type targetType)
{
if (obj is JsonSurrogateObject)
{
return ((JsonSurrogateObject)obj).DeserializedObject;
}
return obj;
}
public Type GetReferencedTypeOnImport(string typeName, string typeNamespace, object customData)
{
return null;
}
#region not implemented
public object GetCustomDataToExport(MemberInfo memberInfo, Type dataContractType)
{
throw new NotImplementedException();
}
public object GetCustomDataToExport(Type clrType, Type dataContractType)
{
throw new NotImplementedException();
}
public void GetKnownCustomDataTypes(Collection<Type> customDataTypes)
{
throw new NotImplementedException();
}
public CodeTypeDeclaration ProcessImportedType(CodeTypeDeclaration typeDeclaration, CodeCompileUnit compileUnit)
{
throw new NotImplementedException();
}
#endregion
}
}
要向类添加新的受支持类型,您只需添加您的类,为其提供正确的构造函数和函数(参见 SurrogateDictionary
示例),确保它继承 JsonSurrogateObject
,并将其类型映射添加到KnownTypes
字典。包含的 SurrogateDictionary 可以作为任何 Dictionary<String,T>
类型的基础,其中 T 是可以正确反序列化的任何类型。
调用它非常简单:
MyObjtype newObj = JsonSurrogate.Deserialize<MyObjtype>(jsonStr, encoding);
请注意,由于某种原因,这个东西在使用包含空格的键字符串时遇到了麻烦;他们根本没有出现在最终名单中。请注意,这可能只是违反了 json 规范,而且我调用的 api 实现得很差;我不知道。无论如何,我通过在原始 json 数据中用下划线替换它们并在反序列化后修复字典来解决这个问题。
Dictionary<String,String>
。老实说,我从来没有尝试过用这个系统反序列化复杂类型。
根据评论above尝试JsonConvert.DeserializeObject<Dictionary<string,dynamic>>(json)
var json = @"{""key1"":1,""key2"":""value2"", ""object1"":{""property1"":""value1"",""property2"":[2,3,4,5,6,7]}}";
var parsedObject = JsonConvert.DeserializeObject<Dictionary<string,dynamic>>(json);
似乎甚至适用于复杂的对象和列表。
我刚刚在 RestSharp 中实现了这一点。 This post 对我很有帮助。
除了链接中的代码,这里是我的代码。现在,当我执行以下操作时,我会得到 Dictionary
个结果:
var jsonClient = new RestClient(url.Host);
jsonClient.AddHandler("application/json", new DynamicJsonDeserializer());
var jsonRequest = new RestRequest(url.Query, Method.GET);
Dictionary<string, dynamic> response = jsonClient.Execute<JObject>(jsonRequest).Data.ToObject<Dictionary<string, dynamic>>();
请注意您所期望的 JSON 类型 - 在我的情况下,我正在检索具有多个属性的单个对象。在附加的链接中,作者正在检索一个列表。
我的方法直接反序列化为 IDictionary,中间没有 JObject 或 ExpandObject。该代码使用转换器,它基本上是从 JSON.NET 源代码中的 ExpandoObjectConverter 类复制而来,但使用 IDictionary 而不是 ExpandoObject。
用法:
var settings = new JsonSerializerSettings()
{
Converters = { new DictionaryConverter() },
};
var result = JsonConvert.DeserializeObject<IDictionary<string, object>>(json, settings);
代码:
// based on ExpandoObjectConverter, but using arrays instead of IList, to behave similar to System.Web.Script.Serialization.JavaScriptSerializer
public class DictionaryConverter : JsonConverter
{
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
{
}
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{
return ReadValue(reader);
}
public override bool CanConvert(Type objectType)
{
return (objectType == typeof(IDictionary<string, object>));
}
public override bool CanWrite
{
get { return false; }
}
private object ReadValue(JsonReader reader)
{
while (reader.TokenType == JsonToken.Comment)
{
if (!reader.Read())
throw JsonSerializationExceptionCreate(reader, "Unexpected end when reading IDictionary<string, object>.");
}
switch (reader.TokenType)
{
case JsonToken.StartObject:
return ReadObject(reader);
case JsonToken.StartArray:
return ReadList(reader);
default:
if (IsPrimitiveToken(reader.TokenType))
return reader.Value;
throw JsonSerializationExceptionCreate(reader, string.Format(CultureInfo.InvariantCulture, "Unexpected token when converting IDictionary<string, object>: {0}", reader.TokenType));
}
}
private object ReadList(JsonReader reader)
{
List<object> list = new List<object>();
while (reader.Read())
{
switch (reader.TokenType)
{
case JsonToken.Comment:
break;
default:
object v = ReadValue(reader);
list.Add(v);
break;
case JsonToken.EndArray:
return list;
}
}
throw JsonSerializationExceptionCreate(reader, "Unexpected end when reading IDictionary<string, object>.");
}
private object ReadObject(JsonReader reader)
{
IDictionary<string, object> dictionary = new Dictionary<string, object>();
while (reader.Read())
{
switch (reader.TokenType)
{
case JsonToken.PropertyName:
string propertyName = reader.Value.ToString();
if (!reader.Read())
throw JsonSerializationExceptionCreate(reader, "Unexpected end when reading IDictionary<string, object>.");
object v = ReadValue(reader);
dictionary[propertyName] = v;
break;
case JsonToken.Comment:
break;
case JsonToken.EndObject:
return dictionary;
}
}
throw JsonSerializationExceptionCreate(reader, "Unexpected end when reading IDictionary<string, object>.");
}
//based on internal Newtonsoft.Json.JsonReader.IsPrimitiveToken
internal static bool IsPrimitiveToken(JsonToken token)
{
switch (token)
{
case JsonToken.Integer:
case JsonToken.Float:
case JsonToken.String:
case JsonToken.Boolean:
case JsonToken.Undefined:
case JsonToken.Null:
case JsonToken.Date:
case JsonToken.Bytes:
return true;
default:
return false;
}
}
// based on internal Newtonsoft.Json.JsonSerializationException.Create
private static JsonSerializationException JsonSerializationExceptionCreate(JsonReader reader, string message, Exception ex = null)
{
return JsonSerializationExceptionCreate(reader as IJsonLineInfo, reader.Path, message, ex);
}
// based on internal Newtonsoft.Json.JsonSerializationException.Create
private static JsonSerializationException JsonSerializationExceptionCreate(IJsonLineInfo lineInfo, string path, string message, Exception ex)
{
message = JsonPositionFormatMessage(lineInfo, path, message);
return new JsonSerializationException(message, ex);
}
// based on internal Newtonsoft.Json.JsonPosition.FormatMessage
internal static string JsonPositionFormatMessage(IJsonLineInfo lineInfo, string path, string message)
{
if (!message.EndsWith(Environment.NewLine))
{
message = message.Trim();
if (!message.EndsWith(".", StringComparison.Ordinal))
message += ".";
message += " ";
}
message += string.Format(CultureInfo.InvariantCulture, "Path '{0}'", path);
if (lineInfo != null && lineInfo.HasLineInfo())
message += string.Format(CultureInfo.InvariantCulture, ", line {0}, position {1}", lineInfo.LineNumber, lineInfo.LinePosition);
message += ".";
return message;
}
}
游戏有点晚了,但上述解决方案都没有为我指明纯粹简单的 .NET 方向,没有 json.net 解决方案。所以就在这里,最终变得非常简单。下面是一个完整的运行示例,说明如何使用标准 .NET Json 序列化完成,该示例在根对象和子对象中都有字典。
黄金子弹是这只猫,将设置解析为序列化程序的第二个参数:
DataContractJsonSerializerSettings settings =
new DataContractJsonSerializerSettings();
settings.UseSimpleDictionaryFormat = true;
完整代码如下:
using System;
using System.Collections.Generic;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Json;
namespace Kipon.dk
{
public class JsonTest
{
public const string EXAMPLE = @"{
""id"": ""some id"",
""children"": {
""f1"": {
""name"": ""name 1"",
""subs"": {
""1"": { ""name"": ""first sub"" },
""2"": { ""name"": ""second sub"" }
}
},
""f2"": {
""name"": ""name 2"",
""subs"": {
""37"": { ""name"": ""is 37 in key""}
}
}
}
}
";
[DataContract]
public class Root
{
[DataMember(Name ="id")]
public string Id { get; set; }
[DataMember(Name = "children")]
public Dictionary<string,Child> Children { get; set; }
}
[DataContract]
public class Child
{
[DataMember(Name = "name")]
public string Name { get; set; }
[DataMember(Name = "subs")]
public Dictionary<int, Sub> Subs { get; set; }
}
[DataContract]
public class Sub
{
[DataMember(Name = "name")]
public string Name { get; set; }
}
public static void Test()
{
var array = System.Text.Encoding.UTF8.GetBytes(EXAMPLE);
using (var mem = new System.IO.MemoryStream(array))
{
mem.Seek(0, System.IO.SeekOrigin.Begin);
DataContractJsonSerializerSettings settings =
new DataContractJsonSerializerSettings();
settings.UseSimpleDictionaryFormat = true;
var ser = new DataContractJsonSerializer(typeof(Root), settings);
var data = (Root)ser.ReadObject(mem);
Console.WriteLine(data.Id);
foreach (var childKey in data.Children.Keys)
{
var child = data.Children[childKey];
Console.WriteLine(" Child: " + childKey + " " + child.Name);
foreach (var subKey in child.Subs.Keys)
{
var sub = child.Subs[subKey];
Console.WriteLine(" Sub: " + subKey + " " + sub.Name);
}
}
}
}
}
}
烦人的是,如果你想使用默认的模型绑定器,看起来你将不得不使用像 POST 这样的数字索引值。
请参阅这篇文章 http://msdn.microsoft.com/en-us/magazine/hh781022.aspx 的以下摘录:
尽管有点违反直觉,但 JSON 请求具有相同的要求——它们也必须遵守表单后命名语法。以之前的 UnitPrice 集合的 JSON 有效负载为例。此数据的纯 JSON 数组语法将表示为: [ { "Code": "USD", "Amount": 100.00 }, { "Code": "EUR", "Amount": 73.64 } ] 但是,默认值值提供者和模型绑定器要求将数据表示为 JSON 表单帖子:{ "UnitPrice[0].Code": "USD", "UnitPrice[0].Amount": 100.00, "UnitPrice[1].Code" : "EUR", "UnitPrice[1].Amount": 73.64 } 复杂的对象收集场景可能是开发人员遇到的最普遍的问题场景之一,因为语法不一定对所有开发人员都很明显。然而,一旦你学会了发布复杂集合的相对简单的语法,这些场景就会变得更容易处理。
您可以使用 Tiny-JSON
string json = "{\"key1\":\"value1\", \"key2\":\"value2\"}";
IDictionary<string, string> dict = Tiny.Json.Decode<Dictionary<string, string>>(json);
我建议使用 .NET 4.5 中的 System.Runtime.Serialization.Json
。
[DataContract]
public class Foo
{
[DataMember(Name = "data")]
public Dictionary<string,string> Data { get; set; }
}
然后像这样使用它:
var serializer = new DataContractJsonSerializer(typeof(List<Foo>));
var jsonParams = @"{""data"": [{""Key"":""foo"",""Value"":""bar""}] }";
var stream = new MemoryStream(Encoding.UTF8.GetBytes(jsonParams));
var obj = serializer.ReadObject(stream);
Console.WriteLine(obj);
这是我使用 System.Text.Json 的解决方案。您将获得嵌套对象的 json 字符串,稍后可以将其转换为所需的类型。
public static Dictionary<string,string> JsonToDictionary(this string json)
{
var objectValues = JsonSerializer.Deserialize<Dictionary<string, object>>(json);
var stringValues = objectValues.Select(o => new KeyValuePair<string, string>(o.Key, o.Value?.ToString()));
return stringValues.ToDictionary(pair => pair.Key, pair => pair.Value);
}
这是从嵌套对象中获取值的用法示例:
var result= json.JsonToDictionary()["outerField"]
.JsonToDictionary()["innerField"];
请注意,此解决方案不涵盖以数组开头的 json 对象,如 [12, 13]。这些对象可以在开始时作为数组读取,然后可以将扩展方法应用于每个项目,以防项目是具有自己属性的复杂对象。
不定期副业成功案例分享
dynamic
作为值的类型:JsonConvert.DeserializeObject<Dictionary<string, dynamic>>(json);
[{key: "a", value: "1"}, {key: "b", value:"2"}]
中使用键值对数组,则不起作用,您必须执行以下操作:var dict = JsonConvert.DeserializeObject<List<KeyValuePair<string, string>>>(json);