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:Usersclusource
eposEdenredLISA_6.0.0.0LISA.CMS.ChileLISA.WebApi.ChileControllersCodeStocksController.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());