String to Object Collection

I Have this String

([{"id":"111","name":"Robocop","cover":"3114188e.jpg"},{"id":"222","name":"Eater","cover":"72dpi.jpg"}])

And is there better way to convert to Object Collection, couse now my crappy code looks like this:

var trimer = myString.TrimStart('(', '[').TrimEnd(')', ']');
string[] coll = trimer.Split('{','}');

string content = "";
foreach(string i in coll)
{
    if (!string.IsNullOrEmpty(i) && i != "," && i != "")
    {
        content += i + "\r\n";
    }
}
string[] contentData = content.Split(new string[] { "\r\n" }, StringSplitOptions.None);

for (int i = 0; i < contentData.Length - 1; i++)
{
    string book = contentData[i].Replace(',','\t').Replace("\"","");
    string[] info = book.Split(new string[] { "\t" }, StringSplitOptions.None);
    string id = info[0];
    string name = info[1];
    string cover = info[2];
}

Upvotes: 1

Views: 94

Answers (1)

Yuval Itzchakov
Yuval Itzchakov

Reputation: 149538

Yes. You actually have a JSON string. You'll need to remove the parenthesis (if they actually exist in the received string) and then you can deserialize it properly. This example uses Json.NET:

public void DeserializeFoo()
{
    var json = "[{\"id\":\"111\",\"name\":\"Robocop\",\"cover\":\"3114188e.jpg\"},
                 {\"id\":\"222\",\"name\":\"Eater\",\"cover\":\"72dpi.jpg\"}]";

    var foos = JsonConvert.DeserializeObject<List<Foo>>(json);
    foreach (var foo in foos)
    {
        Console.WriteLine("Id: {0}", foo.Id);
        Console.WriteLine("Name: {0}", foo.Name);
        Console.WriteLine("Cover: {0}", foo.Cover);
    }
}

public class Foo
{
    [JsonProperty("id")]
    public string Id { get; set; }
    [JsonProperty("name")]
    public string Name { get; set; }
    [JsonProperty("cover")]
    public string Cover { get; set; }
}

Upvotes: 1

Related Questions