Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Deserializing Json String into multiple Object types

I have a Json String that I get from a web service; it has a list of collections, each collection represents an object, for example:

  [ // Root List
    [ // First Collection : Team Object
      {
        "id": 1,
        "team_name": "Equipe Saidi",
        "is_active": true,
        "last_localisation_date": "2015-05-06T13:33:15+02:00"
      },
      {
        "id": 3,
        "team_name": "Equipe Kamal",
        "is_active": true,
        "last_localisation_date": "2015-05-06T09:22:15+02:00"
      }
     ],
     [// Second Collection : user Object
      {
        "id": 1,
        "login": "khalil",
        "mobile_password": "####",
        "first_name": "Abdelali",
        "last_name": "KHALIL",
        "email": "[email protected]",
        "role": "DR",
        "is_active": true,
        "charge": false
      },
      {
        "id": 2,
        "login": "ilhami",
        "mobile_password": "####",
        "first_name": "Abdellah",
        "last_name": "ILHAMI",
        "email": "[email protected]",
        "role": "DR",
        "is_active": true,
        "charge": false
      }
    ]
  ]

My actual code (not working of course ):

 public async Task TeamsAndMobileUsers()
    {
        string data = "";
        IList<User> MobileUsersList = new List<User>();
        IList<Team>  TeamsList  = new List<Team>();
        try
        {
            data = await GetResponse(PATH + TEAMS_USERS_URL);
            TeamsList = JsonConvert.DeserializeObject<List<Team>>(data);   
           MobileUsersList = JsonConvert.DeserializeObject<List<User>>(data); 

            // Inserting
            await SetAchievedActions(TeamsList);

        }
        catch (Exception e) { 
            _errors.Add(e.Message); 
        }
    }

I use Json.net and C#. I can't find a solution, I've read that I should use JsonReader and set its SupportMultipleContent property to true but I don't know how to implement that solution.

like image 701
Kevorkian Avatar asked Jun 02 '15 10:06

Kevorkian


1 Answers

As @YeldarKurmangaliyev already said, your json has two different objects, I think you can do something like this:

var j = JArray.Parse(data);
TeamsList = JsonConvert.DeserializeObject<List<Team>>(j[1].ToString());
MobileUsersList = JsonConvert.DeserializeObject<List<User>>(j[2].ToString());
like image 96
HadiRj Avatar answered Nov 14 '22 23:11

HadiRj