Newtonsoft.Json
https://github.com/JamesNK/Newtonsoft.Json
Json.NET is a popular high-performance JSON framework for .NET http://www.newtonsoft.com/json
Popular high-performance JSON framework for .NET
将json字符串反序列化为dynamic对象
You can use the C# dynamic
type to make things easier. This technique also makes re-factoring simpler as it does not rely on magic-strings.
JSON
The JSON string below is a simple response from an HTTP API call, and it defines two properties: Id
and Name
.
{"Id": 1, "Name": "biofractal"}
C#
Use JsonConvert.DeserializeObject<dynamic>()
to deserialize this string into a dynamic type then simply access its properties in the usual way.
dynamic results = JsonConvert.DeserializeObject<dynamic>(json);
var id = results.Id;
var name= results.Name;
If you specify the type of the results
variable as dynamic
, instead of using the var
keyword, then the property values will correctly deserialize, e.g. Id
to an int
and not a JValue
(thanks to GFoley83 for the comment below).
Note: The NuGet link for the Newtonsoft assembly is http://nuget.org/packages/newtonsoft.json.
latest json.net version allow do this:
dynamic d = JObject.Parse("{number:1000, str:'string', array: [1,2,3,4,5,6]}");
Console.WriteLine(d.number);
Console.WriteLine(d.str);
Console.WriteLine(d.array.Count);
output:
1000
string
6
Documentation here: LINQ to JSON with Json.NET
Json反序列化包含数组的字符串
https://stackoverflow.com/questions/26372250/accessing-items-in-an-json-net-jarray-in-c-sharp
JObject jsonObject = JObject.Parse(requestBody); string header = jsonObject["header"].ToString(Formatting.None); string encryptValue = jsonObject["parameters"].ToString(Formatting.None); MessageHeader messageHeader = JsonConverter.DeSerializer<MessageHeader>(header);
Json反序列化到List<T>
2019-01-23 11:21:51.739+08:00 ERROR [30]: Message:Cannot deserialize the current JSON object (e.g. {"name":"value"}) into type 'System.Collections.Generic.List`1[LISA.Custom.Chile.Entity.API.CodeStockInformationRequest]' because the type requires a JSON array (e.g. [1,2,3]) to deserialize correctly.
To fix this error either change the JSON to a JSON array (e.g. [1,2,3]) or change the deserialized type so that it is a normal .NET type (e.g. not a primitive type like integer, not a collection type like an array or List<T>) that can be deserialized from a JSON object. JsonObjectAttribute can also be added to the type to force it to deserialize from a JSON object.
Path 'header'.
StackTrace: at Newtonsoft.Json.Serialization.JsonSerializerInternalReader.CreateObject(JsonReader reader, Type objectType, JsonContract contract, JsonProperty member, JsonContainerContract containerContract, JsonProperty containerMember, Object existingValue)
at Newtonsoft.Json.Serialization.JsonSerializerInternalReader.Deserialize(JsonReader reader, Type objectType, Boolean checkAdditionalContent)
at Newtonsoft.Json.JsonSerializer.DeserializeInternal(JsonReader reader, Type objectType)
at Newtonsoft.Json.Linq.JToken.ToObject(Type objectType, JsonSerializer jsonSerializer)
at Newtonsoft.Json.Linq.JToken.ToObject(Type objectType)
at Newtonsoft.Json.Linq.JToken.ToObject[T]()
at LISA.WebApi.Chile.Controllers.CodeStocksController.CodeStockInformation(JObject obj) in C:\Users\clu\source\repos\Edenred\LISA_6.0.0.0\LISA.CMS.Chile\LISA.WebApi.Chile\Controllers\CodeStocksController.cs:line 24
method: CodeStockInformation
{
"header": {
"SecurityHash": "92d92f54aca69a57824521f40bccf43e4fd354b15ae9ee4af5b44ac104630e65"
},
"parameters": [
{
"PartnershipIDIdentification": "Partnership1",
"IdCode": "123412318"
},
{
"PartnershipIDIdentification": "Partnership1",
"IdCode": "123412359"
}
]
}
dynamic json = obj; MessageHeader Emp = json.header.ToObject<MessageHeader>(); List<CodeStockInformationRequest> parameters = json.parameters.ToObject<List<CodeStockInformationRequest>>();
解决方案
Your json string is wrapped within square brackets ([]
), hence it is interpreted as array instead of single RetrieveMultipleResponse
object. Therefore, you need to deserialize it to type collection of RetrieveMultipleResponse
, for example :
var objResponse1 =
JsonConvert.DeserializeObject<List<RetrieveMultipleResponse>>(JsonStr);
//JObject obj 方法的参数 dynamic json = obj; List<CodeStockInformationRequest> parameters = JsonConverter.DeSerializer<List<CodeStockInformationRequest>>(json.parameters.ToString());
作者:Chuck Lu GitHub |
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· 没有源码,如何修改代码逻辑?
· 全程不用写代码,我用AI程序员写了一个飞机大战
· DeepSeek 开源周回顾「GitHub 热点速览」
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 记一次.NET内存居高不下排查解决与启示
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了