将Json String反序列化为多个Object类型

时间:2015-06-02 10:44:51

标签: c# json serialization json.net

我有一个从Web服务获得的Json字符串;它有一个集合列表,每个集合代表一个对象,例如:

  [ // 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": "KHALIL@gmail.com",
        "role": "DR",
        "is_active": true,
        "charge": false
      },
      {
        "id": 2,
        "login": "ilhami",
        "mobile_password": "####",
        "first_name": "Abdellah",
        "last_name": "ILHAMI",
        "email": "ILHAMI@gmail.com",
        "role": "DR",
        "is_active": true,
        "charge": false
      }
    ]
  ]

我的实际代码(当然没有工作):

 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); 
        }
    }

我使用Json.net和C#。我无法找到解决方案,我已经读过我应该使用JsonReader并将其SupportMultipleContent属性设置为true,但我不知道如何实现该解决方案。

3 个答案:

答案 0 :(得分:6)

正如@YeldarKurmangaliyev已经说过,你的json有两个不同的对象,我想你可以这样做:

var j = JArray.Parse(data);
TeamsList = JsonConvert.DeserializeObject<List<Team>>(j[1].ToString());
MobileUsersList = JsonConvert.DeserializeObject<List<User>>(j[2].ToString());

答案 1 :(得分:1)

您是否尝试过http://json2csharp.com/为该json生成合约类?另外,第一个和最后一个括号给出了一个无效的JSON

答案 2 :(得分:-4)

You need to create 4 classes
1st class TeamObject : Variable(id,team_name,is_active,last_localisation_date)
2nd class UserObject : Variable (id, login,mobile_password,first_name, last_name ,                        email, role,is_active,charge)
3rd class RootList: Variable ( arraylist<TeamObject> obj, arraylist<UserObject > obj2)
4th class RootClass : Variable(arraylist<RootList> obj)
Gson gson=new Gson();
RootClass dtomodel = gson.fromJson(data , RootClass .class);


This parsing done using Gson Library