1

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

4
  • 3
    just FYI your JSON above is not well-formed. Not sure if it's a typo in the question or you actually copied and pasted from code. Commented Oct 19, 2011 at 15:37
  • @Badescu, I updated my answer to include an example of converting a list of objects in your json string to a C# representation. Commented Oct 19, 2011 at 16:22
  • @Brian the json was written in a hurry by hand, it has been corected. Commented Oct 19, 2011 at 21:56
  • @Frank i have responded to you answer, please look at it Commented Oct 19, 2011 at 21:57

1 Answer 1

2

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

6 Comments

thanks for the reply. what i actually don't know is how to browse the children of an json header, in my example "item". i don't know how to iterate through the json string(i.e. have some sort of 'for' so that i may parse all the items). could you please detail this if you know on my "item" example?
I don't understand why you want to parse it by hand. If you are using Json.NET then you can just deserialize the object, manipulate the object via a foreach and then serialize the object back to Json.
because it doesn't work the way you showed me. Here is my code :
List<Restaurant> RList = JsonConvert.DeserializeObject<List<Restaurant>>(json); foreach (Restaurant R in RList) { Console.WriteLine(R.name); }
it says that it can't deserialize into generic list
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.