How to deserialize with JSON.NET?
How do I setup Newtonsoft Json.net to deserialize this text into a .NET object?
[
[
开发者_JAVA技巧 "US\/Hawaii",
"GMT-10:00 - Hawaii"
],
[
"US\/Alaska",
"GMT-09:00 - Alaska"
],
]
For bonus points, what is this kind of structure called in Json. I tried looking for anonymous objects, but didn't have any luck.
This JSON string (or almost, it will be a valid JSON after you fix it and remove the trailing comma, as right now it's invalid) represents an array of arrays of strings. It could be easily deserialized into a string[][]
using the built into .NET JavaScriptSerializer class:
using System;
using System.Web.Script.Serialization;
class Program
{
static void Main()
{
var json =
@"[
[
""US\/Hawaii"",
""GMT-10:00 - Hawaii""
],
[
""US\/Alaska"",
""GMT-09:00 - Alaska""
]
]";
var serializer = new JavaScriptSerializer();
var result = serializer.Deserialize<string[][]>(json);
foreach (var item in result)
{
foreach (var element in item)
{
Console.WriteLine(element);
}
}
}
}
and the exactly same result could be achieved with JSON.NET using the following:
var result = JsonConvert.DeserializeObject<string[][]>(json);
JSON.Net uses JArray
to allow these to be parsed - see:
- Deserializing variable Type JSON array using DataContractJsonSerializer (the questions is about DataContract - but the answer is about JSON.Net - and is from JSON.Net's author)
- Json.NET: serializing/deserializing arrays
To see a blog entry detailing how to serialize and deserialize between .NET and JSON, check this out. I found it really helpful.
精彩评论