9

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.

3

4 Answers 4

11

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
Sign up to request clarification or add additional context in comments.

2 Comments

I accept your answer as I've finally used something similar from the link in the question comments. What is this DataMember decorator added for ?
Thanks! I think that the name in the DataMember attribute is used to mapp your JSON-property to your instance property. Read more about the DataMemberhere
4

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; }
}

Comments

2

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.

Comments

1

Answer of nekman is not completely correct, the attribute should be JsonPropery instead of DataMember. (in this case you can remove the attribute since the deserializer doesn't care about the capital H)

public class HtmlItem
{
   [JsonProperty("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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.