1

I have next json:

{
  "foo": "foo",
  "bars": {
             "bar": [
             {
               "a":"b",
               "c":"d"
             },
            {
               "a":"b",
               "c":"d"
             },
                   ]
           }
}

As you can see there is property that contains array. How can i deserialize this json into next class signature

class SomeClass
{
     public string foo{ get;set;}
     public IEnumerable<bar> {get;set;}
}

instead of

class SomeClass
{
     public string foo{ get;set;}
     public Bars bars {get;set;}
}
class Bars
{
     public IEnumerable<bar> {get;set;}
}

?

Anton Shakalo
  • 437
  • 1
  • 6
  • 23
  • http://stackoverflow.com/questions/7895105/json-deserialize-c-sharp – Paul Michaels Dec 10 '13 at 12:32
  • It is not I need. I need to remove extra property in resulting class. – Anton Shakalo Dec 10 '13 at 12:36
  • Check out this [post](http://stackoverflow.com/questions/20448379/deserialize-object-using-json-net-without-the-need-for-a-container/20458000#20458000). The same topic is discussed, the format of the json object is a little different, but it also has an extra property. – Ilija Dimov Dec 10 '13 at 14:13
  • Ok, I can do this. I hoped that I can do this with json.net attributes. – Anton Shakalo Dec 10 '13 at 14:26

2 Answers2

0

this code should work if you made some modifications to your json:

var myObj = new JavaScriptSerializer().Deserialize<SomeClass>(json);

your json:

{
  "foo": "foo",
  "bars": /*{
             "bar": this should be removed*/
             [
                 {
                   "a":"b",
                   "c":"d"
                 },
                 {
                   "a":"b",
                   "c":"d"
                 } /*, and this comma*/
             ]
         /*} and this closing bracket too*/
    }
0

You can create a public list that maps to the class:

class SomeClass
{
  public string foo{ get;set;}
  private BarItems bars {get;set;}     

  public IEnumerable<Bar> Bars
  {
    get
    {
      return bars.bar ?? new IEnumerable<Bar>();
    }
    set
    {
      bars.bar = value;
    }
  }
}


class BarItems
{
     public IEnumerable<Bar> bar {get;set;}
}

It least makes the object more usable when working with it.

Hairy Goat
  • 43
  • 5