简体   繁体   中英

Deserialize multiple JSON arrays into separate C# datasets/datatables using JSON.net (newtonsoft)

Im trying for hours now to get the following two JSON arrays (namely clients and dossiers) into two separate datasets/datatables using Newtonsoft JSON.net in C#:

{
   "status": "OK",
   "clients": [
    {
        "ClientID": "123456",
        "Fullname": "John Doe",
        "Inactive": false
    },
    {
        "ClientID": "234567",
        "Fullname": "James Smith",
        "Inactive": false
    }
   ],
   "dossiers": [
    {
        "CreateDate": "03.06.2013",
        "DossierName": "JD20130603"
    },
    {
        "CreateDate": "04.06.2013",
        "DossierName": "JS20130604"
    }
    ]
}

Can someone please help? Thanks in advance...

EDIT: I would like to avoid the whole Class thing if possible.

EDIT 2: So far Ive tried the following approaches

var _clientlist = JObject.Parse(_jsonresp)["clients"].Children();

Which works, but I cannot get the values into a dataset/datable

_clientlist = (DataTable)JsonConvert.DeserializeObject(_jsonresp, (typeof(DataTable)));

Fails :(

DataSet _dataset = JsonConvert.DeserializeObject<DataSet>(_jsonresp);
DataTable _clientlist = _dataset.Tables["clients"];

Similar process to above but same result

dynamic _d = JValue.Parse(_response);
JArray _jsonval = JArray.Parse(_d.clients) as JArray;

Fails :(

At which point I gave up.

This doesn't answer the question exactly because I personally don't see why you would want to deserialize into datasets when the json.NET model is more oriented around deserializing into objects. Here it is;

public class TheJson
{
    public string status { get; set; }
    public client[] clients { get; set; }
    public dossier[] dossiers { get; set; }
}


public class client
{
     public string ClientID { get; set; }
     public string Fullname { get; set; }
     public bool Inactive { get; set; }
}

public class dossier
{
     public string CreateDate { get; set; }
     public string DossierName { get; set; }
}

With those definitions it's as simple as;

TheJson clientsAndDossiers = JsonConvert.DeserializeObject<TheJson>(_jsonresp);

Now with regard to your last comment, to apply search filters I would just use LINQ. Like for example if I want to get only active clients I could do;

List<client> activeClients = clientsAndDossiers.clients.Where(x => x.Inactive == false).ToList();

With regard your comment on this post, here is the LINQ implementation;

string inputString = MenuSearchBox.Text.ToString();
List<client> filtered = clientsAndDossiers.clients.Where(x => x.Fullname.Contains(inputString)).ToList();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM