Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to deserialize JSON array of objects to c# structure

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.

like image 861
mike_hornbeck Avatar asked Dec 30 '12 23:12

mike_hornbeck


3 Answers

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
like image 138
nekman Avatar answered Oct 15 '22 07:10

nekman


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; }
}
like image 32
Sergey Berezovskiy Avatar answered Oct 15 '22 09:10

Sergey Berezovskiy


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.

like image 31
evanmcdonnal Avatar answered Oct 15 '22 09:10

evanmcdonnal