Reputation: 11157
i have a json like this
"[{ "item" : { "id":1 , "name":"abc" } , "item" : { "id":1 , "name":"abc" } ]"
How can i parse the items and save them as Item(a class defined by me) in this json using (Linq) JSON.NET?
i found http://james.newtonking.com/pages/json-net.aspx but i don't know how to parse list of objects (item) considering in this case there are multiple 'item's and each 'item' is composed from other data
Upvotes: 1
Views: 1459
Reputation: 1896
It's pretty simple actually:
YourClass foo = JsonConvert.DeserializeObject<YourClass>(YourJSONString);
EDIT #1:
But you asked about converting an array and I missed that. I'm sure it's still pretty easy to do even if your JSON is an array of those objects. I just wrote up this little example but I'm using a list instead of an array:
List<string> foo = new List<string>() { "Hello", "World" };
string serialized = JsonConvert.SerializeObject(foo);
List<string> bar = JsonConvert.DeserializeObject<List<string>>(serialized);
foreach (string s in bar)
{
Console.WriteLine(s);
}
EDIT #2:
I made a change to your Json string because it wouldn't work the way you had it.
public class item
{
public int id { get; set; }
public string name { get; set; }
}
string json = "[{\"item\" : { \"id\":1 , \"name\":\"abc\" }} , {\"item\" : { \"id\":1 , \"name\":\"abc\"}}]";
List<item> items = JsonConvert.DeserializeObject<List<item>>(json);
Upvotes: 2