I have a json string that was created from serializing an array of objects :
[
{
"html": "foo"
},
{
"html": "bar"
}
]
How can I deserialize it to some iterable C# structure ? I've tried this code, but I'm getting No parameterless constructor defined for type of 'System.String'.
error :
string[] htmlArr = new JavaScriptSerializer().Deserialize<String[]>(html);
What I want to receive is an iterable structure to get each 'html' object.
Use a class for each JSON object. Example:
public class HtmlItem
{
[DataMember(Name = "html")]
public string Html { get; set; }
}
JavaScriptSerializer ser = new JavaScriptSerializer();
// Serialize
string html = ser.Serialize(new List<HtmlItem> {
new HtmlItem { Html = "foo" },
new HtmlItem { Html = "bar" }
});
// Deserialize and print the html items.
List<HtmlItem> htmlList = ser.Deserialize<List<HtmlItem>>(html);
htmlList.ForEach((item) => Console.WriteLine(item.Html)); // foo bar
You can use Newtonsoft Json.NET (available from NuGet)
string json = @"[{""html"": ""foo""},{""html"": ""bar""}]";
var items = JsonConvert.DeserializeObject<List<Item>>(json);
Where
public class Item
{
public string Html { get; set; }
}
The docs site apparently isn't working right now... But I would try using JSON.NET ( http://james.newtonking.com/projects/json/help/ )
There are a couple of ways you can do it. You can deserialize in a very dynamic not type strict way or you can define an object that matches the json object exactly and deserialize into that. If there are many formats of JSON you'll have to serialize I would recommend using schemas.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With