I have a json string like this;
[
{
"ID": 123456789,
"userInf": {
"Name": "NameSurname1",
"Adress": "example adress"
},
"price": "3898.30",
"kdv": "701.69",
"total": "4599,99",
"note": "example note"
},
{
"ID": 98756431,
"userInf": {
"Name": "NameSurname2",
"Adress": "example address2"
},
"price": "1116.10",
"kdv": "82.90",
"total": "1199.00",
"note": "example note2"
}
]
And build up classes like this;
public partial class Sale
{
public long ID { get; set; }
public UserInf UserInf { get; set; }
public string Price { get; set; }
public string Kdv { get; set; }
public string Total { get; set; }
public string note { get; set; }
}
public partial class UserInf
{
public string Name { get; set; }
public string Adress { get; set; }
}
And I call json with this code and deserialize;
var data = JsonConvert.DeserializeObject<Sale>(jsonstring);
var shapedData = Enumerable.Range(0, 1).Select(x =>
new
{
ID = data.ID,
userInf = data.UserInf.Name,
price = data.Price,
kdv = data.Kdv,
total = data.Total,
note= data.Note
}).ToList();
DataTable dt = ToDataTable(shapedData);
dataGridView1.DataSource = dt;
and I get error. But if I change my json and cut the second half and delete the [,] symbols code just works perfectly fine. I need to deserialize multiple like above and tried multiple ways to deserialize but this is the closest way I get so far.
I get the error on this line ;
var data = JsonConvert.DeserializeObject<Sale>(jsonstring);
Error is
Cannot deserialize the current JSON array (e.g. [1,2,3]) into type .. and so.
I know I'm missing something very basic but I have no coder friend to ask.
I would be grateful if you could suggest a better way to do it.
You should deserialize it as collection;
JsonConvert.DeserializeObject<List<Sale>>(jsonstring);
And your linq query looks like;
var shapedData = data.Select(x =>
new
{
ID = x.ID,
userInf = x.UserInf.Name,
price = x.Price,
kdv = x.Kdv,
total = x.Total,
note = x.note
}).ToList();
can you try like this , dont make use of var as you already know return type
List<Sale> data = JsonConvert.DeserializeObject<List<Sale>>(jsonstring);
as your string return array of data
Related
I have a json text and i want to get the values of author name and description tags. no need of other fields like url and urltoimage and all.
when i run the below code does not providing any string values. i think some error goes here.
{
"status": "ok",
"articles": [
{
"source": {
"id": "techcrunch",
"name": "TechCrunch"
},
"author": "Khaled \"Tito\" Hamze",
"title": "Crunch Report",
"description": "Your daily roundup of the biggest TechCrunch stories and startup news.",
"url": "https://techcrunch.com/video/crunchreport/",
"urlToImage": "https://tctechcrunch2011.files.wordpress.com/2015/03/tccrshowogo.jpg?w=500&h=200&crop=1",
"publishedAt": "2017-12-11T20:20:09Z"
},
{
"source": {
"id": "techcrunch",
"name": "TechCrunch"
},
"author": "Sarah Perez",
"title": "Facebook is trying to make the Poke happen again",
"description": "Facebook's \"Poke\" feature has never really gone away, but now the social network is giving it a more prominent placement - and is even considering expanding..",
"url": "https://techcrunch.com/2017/12/11/facebook-is-trying-to-make-the-poke-happen-again/",
"urlToImage": "https://tctechcrunch2011.files.wordpress.com/2017/12/facebook-poke-icon.jpg",
"publishedAt": "2017-12-11T20:02:30Z"
},
{
"source": {
"id": "techcrunch",
"name": "TechCrunch"
},
"author": "Sarah Perez",
"title": "Amazon Alexa can now wake you up to music",
"description": "This fall, Amazon made a play to become your new alarm clock with the introduction of a combination smart speaker and clock called the Echo Spot. Today, the..",
"url": "https://techcrunch.com/2017/12/11/amazon-alexa-can-now-wake-you-up-to-music/",
"urlToImage": "https://tctechcrunch2011.files.wordpress.com/2017/09/amazon-event-9270069.jpg",
"publishedAt": "2017-12-11T17:22:30Z"
},
{
"source": {
"id": "techcrunch",
"name": "TechCrunch"
},
"author": "Ingrid Lunden, Katie Roof",
"title": "Apple confirms Shazam acquisition; Snap and Spotify also expressed interest",
"description": "After we broke the story last week that Apple was acquiring London-based music and image recognition service Shazam, Apple confirmed the news today. It is..",
"url": "https://techcrunch.com/2017/12/11/apple-shazam-deal/",
"urlToImage": "https://tctechcrunch2011.files.wordpress.com/2017/12/shazam-app-icon-ios.jpg",
"publishedAt": "2017-12-11T15:59:31Z"
}
]}
how to get this? below is my code and its not at all working
var data = (JObject)JsonConvert.DeserializeObject(myJSON);
string nameArticles= data["articles"].Value<string>();
MessageBox.Show(nameArticles);
public class Source
{
public string id { get; set; }
public string name { get; set; }
}
public class Article
{
public Source source { get; set; }
public string author { get; set; }
public string title { get; set; }
public string description { get; set; }
public string url { get; set; }
public string urlToImage { get; set; }
public DateTime publishedAt { get; set; }
}
Article art = new Article();
art = JsonConvert.DeserializeObject<Article>(myJSON);
MessageBox.Show(art.description.ToString());
the above code return object not set to an instance error!
data["articles"] is likely to be a JArray not a string. You'll need to iterate over each JObject in the aforementioned JArray pulling out the author and description values
var data = (JObject)JsonConvert.DeserializeObject(myJSON);
var articles = data["articles"].Children();
foreach (var article in articles)
{
var author = article["author"].Value<string>();
var description = article["author"].Value<string>();
Console.WriteLine($"Author: " + author + ", Description: " + description);
}
This should help you get started with whatever you're doing.
If you do not want to create a wrapper class, you can try the below code snippet, which uses the dynamic type to deserialize JSON into an object.
var json = "Your JSON string";
dynamic stuff = JsonConvert.DeserializeObject(json);
string name = stuff.status;
var arr = stuff.articles;
foreach (var a in arr)
{
var authorName = a.author;
}
Assuming you wish to deserialize to concrete classes (as per the second attempted approach shown in your question) then you need a wrapper class to hold the whole object, and deserialise to that.
At the moment you're trying to serialise your entire object into an Article, but only the individual objects within the articles array of that object would match the structure in your Article class.
You're trying to do the action at the wrong level of your object, and also you're forgetting the fact that articles is a list (array).
Something like this:
public class JSONResponse
{
public string status { get; set; }
public List<Article> articles { get; set; }
}
and
JSONResponse response = JsonConvert.DeserializeObject<JSONResponse>(myJSON);
Then you can use a normal loop to iterate through the response.articles list and extract the author names and descriptions.
sample json data
string jsonString = "{\"displayName\":\"Alex Wu\",\"signInNames\":[{\"type\":\"emailAddress\",\"value\":\"AlexW#example.com\"},{\"type\":\"emailAddress\",\"value\":\"AlexW2#example.com\"}]}";
Convert json into jObject and get values using inbuilt method called selectToken()
JObject jObject = JObject.Parse(jsonString);
string displayName = (string)jObject.SelectToken("displayName");
string type = (string)jObject.SelectToken("signInNames[0].type");
string value = (string)jObject.SelectToken("signInNames[0].value");
Console.WriteLine("{0}, {1}, {2}", displayName, type, value);
JArray signInNames = (JArray)jObject.SelectToken("signInNames");
foreach (JToken signInName in signInNames)
{
type = (string)signInName.SelectToken("type");
value = (string)signInName.SelectToken("value");
Console.WriteLine("{0}, {1}", type, value);
}
Thank you
Your Json make below set of class
public class Source
{
public string id { get; set; }
public string name{get;set;}
}
public class Article
{
public Source source { get; set; }
public string author { get; set; }
public string title { get; set; }
public string description { get; set; }
public string url { get; set; }
public string urlToImage { get; set; }
public DateTime publishedAt { get; set; }
}
public class RootObject
{
public string status { get; set; }
public List<Article> articles { get; set; }
}
So You Deserialize this by following way..
var data = JsonConvert.DeserializeObject<RootObject>(myJSON);
nameArticles=data.articles.FirstOrDefault().description;
MessageBox.Show(nameArticles);
Please create a class for your JSON file and add property for all tags
and then write code as below:
public class exampleJson{
public string author {get;set;}
public string description {get;set;}
.....
}
var data = JsonConvert.DeserializeObject<exampleJson>(myJSON);
string authorName = data.author;
string descriptions = data.description ;
JSON
{
"count": 3,
"value": [
{
"id": "AAAAAAAAAAAAA",
"description": "test1",
"name": "name1"
},
{
"id": "BBBBBBBBBB",
"description": "test2",
"name": "name2"
},
{
"id": "CCCCCCCCCCCC",
"description": "test3",
"name": "name3"
}
]
}
I have a code in my solution retrieving from a LIST api and giving the JSON above.
How can I use a LINQ to retrieve specific values? (e.g) I need to select name1 and I will get the id,description,name values.
I am using a dynamic variable in my code:
dynamic json = JObject.Parse(client.GetString().Result);
I'd been tinkering with other online guides the past few hours. However, can't get the result right.
Please help.
One solution would be to deserialize your JSON string into C# objects and then use Linq to get a specific object.
C# class definitions:
public class Content
{
[JsonProperty("count")]
public int Count { get; set; }
[JsonProperty("value")]
public List<Value> Values { get; set; }
public Content()
{
Values = new List<Value>();
}
}
public class Value
{
[JsonProperty("id")]
public string Id { get; set; }
[JsonProperty("description")]
public string Description { get; set; }
[JsonProperty("name")]
public string Name { get; set; }
}
Deserializing and getting the object:
string json = #"{
""count"": 3,
""value"": [
{
""id"": ""AAAAAAAAAAAAA"",
""description"": ""test1"",
""name"": ""name1""
},
{
""id"": ""BBBBBBBBBB"",
""description"": ""test2"",
""name"": ""name2""
},
{
""id"": ""CCCCCCCCCCCC"",
""description"": ""test3"",
""name"": ""name3""
}
]
}";
Content content = JsonConvert.DeserializeObject<Content>(json);
Value value = content.Values.FirstOrDefault(x => x.Name.Equals("name1", StringComparison.InvariantCultureIgnoreCase));
First, you can create a class to represent a client:
public class Client
{
public string Id { get; set; }
public string Description { get; set; }
public string Name { get; set; }
}
With this class, you can use JObject.Parse (as you're already doing) to parse the JSON into something that can be queried, use SelectToken to pull out the value array and then use ToObject to convert that to a list of Clients. Here's what that looks like:
var jsonObject = JObject.Parse(json_source);
var jsonObjectValue = jsonObject.SelectToken("value");
var clients = jsonObjectValue.ToObject<List<Client>>();
Once you've got your clients variable, you can use a simple LINQ statement to find the one that is name1:
var clientWithName1 = clients.SingleOrDefault(x => x.Name == "name1");
In this case, clientWithName will be null if no such client was found.
Here's a dotnetfiddle that demonstrates a complete solution.
Create an object Client that has properties id, description and name. Deserialize the json into a list of these objects.
List<Client> clients = JsonConvert.Deserialize<List<Client>>(json_source);
string desc = clients[0].description;
Apparently with fiddling with my code I found an answer for myself.
Thanks for to the ones trying to help me for giving me ideas.
var requestWorkProcess = await client.GetStringAsync("my url");
var workProcessId = JObject.Parse(requestWorkProcess)["value"].Children<JObject>().FirstOrDefault(o => o["name"].ToString() == workProcess).GetValue("id");
I have a json text and i want to get the values of author name and description tags. no need of other fields like url and urltoimage and all.
when i run the below code does not providing any string values. i think some error goes here.
{
"status": "ok",
"articles": [
{
"source": {
"id": "techcrunch",
"name": "TechCrunch"
},
"author": "Khaled \"Tito\" Hamze",
"title": "Crunch Report",
"description": "Your daily roundup of the biggest TechCrunch stories and startup news.",
"url": "https://techcrunch.com/video/crunchreport/",
"urlToImage": "https://tctechcrunch2011.files.wordpress.com/2015/03/tccrshowogo.jpg?w=500&h=200&crop=1",
"publishedAt": "2017-12-11T20:20:09Z"
},
{
"source": {
"id": "techcrunch",
"name": "TechCrunch"
},
"author": "Sarah Perez",
"title": "Facebook is trying to make the Poke happen again",
"description": "Facebook's \"Poke\" feature has never really gone away, but now the social network is giving it a more prominent placement - and is even considering expanding..",
"url": "https://techcrunch.com/2017/12/11/facebook-is-trying-to-make-the-poke-happen-again/",
"urlToImage": "https://tctechcrunch2011.files.wordpress.com/2017/12/facebook-poke-icon.jpg",
"publishedAt": "2017-12-11T20:02:30Z"
},
{
"source": {
"id": "techcrunch",
"name": "TechCrunch"
},
"author": "Sarah Perez",
"title": "Amazon Alexa can now wake you up to music",
"description": "This fall, Amazon made a play to become your new alarm clock with the introduction of a combination smart speaker and clock called the Echo Spot. Today, the..",
"url": "https://techcrunch.com/2017/12/11/amazon-alexa-can-now-wake-you-up-to-music/",
"urlToImage": "https://tctechcrunch2011.files.wordpress.com/2017/09/amazon-event-9270069.jpg",
"publishedAt": "2017-12-11T17:22:30Z"
},
{
"source": {
"id": "techcrunch",
"name": "TechCrunch"
},
"author": "Ingrid Lunden, Katie Roof",
"title": "Apple confirms Shazam acquisition; Snap and Spotify also expressed interest",
"description": "After we broke the story last week that Apple was acquiring London-based music and image recognition service Shazam, Apple confirmed the news today. It is..",
"url": "https://techcrunch.com/2017/12/11/apple-shazam-deal/",
"urlToImage": "https://tctechcrunch2011.files.wordpress.com/2017/12/shazam-app-icon-ios.jpg",
"publishedAt": "2017-12-11T15:59:31Z"
}
]}
how to get this? below is my code and its not at all working
var data = (JObject)JsonConvert.DeserializeObject(myJSON);
string nameArticles= data["articles"].Value<string>();
MessageBox.Show(nameArticles);
public class Source
{
public string id { get; set; }
public string name { get; set; }
}
public class Article
{
public Source source { get; set; }
public string author { get; set; }
public string title { get; set; }
public string description { get; set; }
public string url { get; set; }
public string urlToImage { get; set; }
public DateTime publishedAt { get; set; }
}
Article art = new Article();
art = JsonConvert.DeserializeObject<Article>(myJSON);
MessageBox.Show(art.description.ToString());
the above code return object not set to an instance error!
data["articles"] is likely to be a JArray not a string. You'll need to iterate over each JObject in the aforementioned JArray pulling out the author and description values
var data = (JObject)JsonConvert.DeserializeObject(myJSON);
var articles = data["articles"].Children();
foreach (var article in articles)
{
var author = article["author"].Value<string>();
var description = article["author"].Value<string>();
Console.WriteLine($"Author: " + author + ", Description: " + description);
}
This should help you get started with whatever you're doing.
If you do not want to create a wrapper class, you can try the below code snippet, which uses the dynamic type to deserialize JSON into an object.
var json = "Your JSON string";
dynamic stuff = JsonConvert.DeserializeObject(json);
string name = stuff.status;
var arr = stuff.articles;
foreach (var a in arr)
{
var authorName = a.author;
}
Assuming you wish to deserialize to concrete classes (as per the second attempted approach shown in your question) then you need a wrapper class to hold the whole object, and deserialise to that.
At the moment you're trying to serialise your entire object into an Article, but only the individual objects within the articles array of that object would match the structure in your Article class.
You're trying to do the action at the wrong level of your object, and also you're forgetting the fact that articles is a list (array).
Something like this:
public class JSONResponse
{
public string status { get; set; }
public List<Article> articles { get; set; }
}
and
JSONResponse response = JsonConvert.DeserializeObject<JSONResponse>(myJSON);
Then you can use a normal loop to iterate through the response.articles list and extract the author names and descriptions.
sample json data
string jsonString = "{\"displayName\":\"Alex Wu\",\"signInNames\":[{\"type\":\"emailAddress\",\"value\":\"AlexW#example.com\"},{\"type\":\"emailAddress\",\"value\":\"AlexW2#example.com\"}]}";
Convert json into jObject and get values using inbuilt method called selectToken()
JObject jObject = JObject.Parse(jsonString);
string displayName = (string)jObject.SelectToken("displayName");
string type = (string)jObject.SelectToken("signInNames[0].type");
string value = (string)jObject.SelectToken("signInNames[0].value");
Console.WriteLine("{0}, {1}, {2}", displayName, type, value);
JArray signInNames = (JArray)jObject.SelectToken("signInNames");
foreach (JToken signInName in signInNames)
{
type = (string)signInName.SelectToken("type");
value = (string)signInName.SelectToken("value");
Console.WriteLine("{0}, {1}", type, value);
}
Thank you
Your Json make below set of class
public class Source
{
public string id { get; set; }
public string name{get;set;}
}
public class Article
{
public Source source { get; set; }
public string author { get; set; }
public string title { get; set; }
public string description { get; set; }
public string url { get; set; }
public string urlToImage { get; set; }
public DateTime publishedAt { get; set; }
}
public class RootObject
{
public string status { get; set; }
public List<Article> articles { get; set; }
}
So You Deserialize this by following way..
var data = JsonConvert.DeserializeObject<RootObject>(myJSON);
nameArticles=data.articles.FirstOrDefault().description;
MessageBox.Show(nameArticles);
Please create a class for your JSON file and add property for all tags
and then write code as below:
public class exampleJson{
public string author {get;set;}
public string description {get;set;}
.....
}
var data = JsonConvert.DeserializeObject<exampleJson>(myJSON);
string authorName = data.author;
string descriptions = data.description ;
I am getting familiar with C# and Linq and appreciate any help. It should be easy for someone who works with it. I have a Json object that returns contact information. I also have a list of ids. I need to compare the list to the Json object and wherever the value in the list matches the userclientcode in the Json object, I need to extract the following information (only for the matches):
clienttaxonomy (if not empty)
fullname (if not empty)
[0]contactdata ( -> email if not null or empty)
[1]contactdata (-> address if not null or empty)
[2]contactdata (-> phone number if not null or empty)
First List
var fileContactIds = new List<string> { "5678765", "2135123", "12341234", "341234123", "12341234123", "2341234123", "341234123", "123412341", "13342354",
"12342341", "123412322", "163341234", "2345234115", "8967896", "75626234 };
JSON object returned with:
return JsonConvert.DeserializeObject<RelatedContacts>(json)?.list;
This is the Json object:
[![Json object][1]][1]
This is the Json string (unescaped):
{
"type": "com.kurtosys.api.userprofile.domain.RelatedContactList",
"list": [{
"objectlistid": 5678765,
"objectlisttypeid": 4567876,
"objectlistname": "ALL.National",
"clienttaxonomyid": 765677,
"clienttaxonomy": "National Wholesaler",
"order": 1,
"contacts": [{
"personid": 7654345678,
"fullname": "Person Jallo",
"userid": 876567,
"userclientcode": "341234123",
"contactdetails": [{
"contactid": 8765567,
"contacttypeid": 4565,
"contactdata": "person.contact#site.com"
}, {
"contactid": 876545678,
"contacttypeid": 4565,
"contactdata": "Baltimore,MD,21209,United States"
}, {
"contactid": 87654567,
"contacttypeid": 4584,
"contactdata": "410-413-2640"
}]
}]
}, {
"objectlistid": 765678,
"objectlisttypeid": 40400461,
"objectlistname": "RM.Internal",
"clienttaxonomyid": 7567898,
"clienttaxonomy": "Internal Regional Wholesaler",
"order": 2,
"contacts": [{
"personid": 56789876,
"fullname": "Jackson Man",
"userid": 876567,
"userclientcode": "1012275",
"contactdetails": [{
"contactid": 309598309,
"contacttypeid": 76546,
"contactdata": "mister.jackson##site.com.com"
}, {
"contactid": 876567,
"contacttypeid": 4581,
"contactdata": "Baltimore,MD,21209,United States"
}, {
"contactid": 876567,
"contacttypeid": 2342,
"contactdata": "123-413-2604"
}]
}]
}, {
"objectlistid": 309571364,
"objectlisttypeid": 40400461,
"objectlistname": "RM.External",
"clienttaxonomyid": 309580710,
"clienttaxonomy": "External Regional Wholesaler",
"order": 3,
"contacts": [{
"personid": 302736188,
"fullname": "Phal Sumi",
"userid": 303826019,
"userclientcode": "163341234",
"contactdetails": [{
"contactid": 309598253,
"contacttypeid": 2342,
"contactdata": "misters.emailas#site.com"
}, {
"contactid": 309611930,
"contacttypeid": 2342,
"contactdata": "Baltimore,MD,21209,United States"
}, {
"contactid": 34234132,
"contacttypeid": 3422,
"contactdata": "342-803-1793"
}]
}]
}]
}
How do I
1] Select using Linq and Lambdas and put in a list fullname, email, address etc from the deserialized object ?
2]compare with first list and only transfer those items where the userclientcode == the number in list A.
I have tried:
var query5 = relatedContact.Where(s => s.objectlistid == Convert.ToInt64(contacts.Select(t => t.id)))
var selected = relatedContact.Where(p => p.contacts
.Any(a => fileContactIds.Contains(p.contacts))
.ToList();
var query2 = relatedContact.Where(s => s.objectlistid == Convert.ToInt64(contacts.Select(t => t.id)))
.Select(s => new
{
Description = s.clienttaxonomy,
Fullname = s.contacts[0].fullname,
Email = s.contacts[0].contactdetails[0].contactdata,
Address = s.contacts[0].contactdetails[1].contactdata,
PhoneNumber = s.contacts[0].contactdetails[2].contactdata
});
But don't really know what I'm doing it seems. Any suggestions on how to get the required sections ? I think part of the reason is that the contactdata is a list.
Thanks all
You can create a classes for the desearlization of JSON Object like this
public class Rootobject
{
public string type { get; set; }
public List[] list { get; set; }
}
public class List
{
public int objectlistid { get; set; }
public int objectlisttypeid { get; set; }
public string objectlistname { get; set; }
public int clienttaxonomyid { get; set; }
public string clienttaxonomy { get; set; }
public int order { get; set; }
public Contact[] contacts { get; set; }
}
public class Contact
{
public long personid { get; set; }
public string fullname { get; set; }
public int userid { get; set; }
public string userclientcode { get; set; }
public Contactdetail[] contactdetails { get; set; }
}
public class Contactdetail
{
public int contactid { get; set; }
public int contacttypeid { get; set; }
public string contactdata { get; set; }
}
And then to extract the selected information we can also create a another class like
public class ExtractedInfo
{
public string ocClientTaxonomy { get; set; }
public string ocFullName { get; set; }
public CTDetails ocContactDetails { get; set; }
}
public class CTDetails
{
public string ocCTAddress { get; set; }
public string ocCTEmail { get; set; }
public string ocCTPhoneNumber { get; set; }
}
Now we have to find all the data from JSON
var fileContactIds = new List<string> { "5678765", "2135123", "12341234", "341234123", "12341234123", "2341234123", "341234123", "123412341", "13342354", "12342341", "123412322", "163341234", "2345234115", "8967896", "75626234" };
//Read JSON from txt file. You can do it by your way
string myjson = File.ReadAllText("Some.txt");
string ctphno, ctadd, ctemail, cltax, ctfullname;
List<ExtractedInfo> ei = new List<ExtractedInfo>();
CTDetails ctdtl = new CTDetails();
ExtractedInfo eiex = new ExtractedInfo();
//Deserialize the JSON string to Object.
Rootobject AllData = JsonConvert.DeserializeObject<Rootobject>(myjson);
//Finding all data in List Class
foreach(List lst in AllData.list)
{
cltax = lst.clienttaxonomy; // you can directly put eiex.ocClientTaxonomy = lst.clienttaxonomy;
foreach(Contact ct in lst.contacts)
{
//To check if value in the list matches the objectlistid in the Json object
if(fileContactIds.Contains(lst.objectlistid.ToString()))
{
ctfullname = ct.fullname; // you can directly put eiex.ocFullName = ct.fullname;
foreach(Contactdetail ctd in ct.contactdetails)
{
//Here we are trying to find the Match for Email.
if(Regex.IsMatch(ctd.contactdata, #"\A(?:[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*#(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?)\Z", RegexOptions.IgnoreCase))
{
ctemail = ctd.contactdata;
ctdtl.ocCTEmail = ctemail;
}
//Here We trying to find the match for Phone Number.
else if(Regex.IsMatch(ctd.contactdata, #"\(?\d{3}\)?-? *\d{3}-? *-?\d{4}", RegexOptions.IgnoreCase))
{
ctphno = ctd.contactdata;
ctdtl.ocCTPhoneNumber = ctphno;
}
//If NOthing matches than it might be address (Assumed)
else
{
ctadd = ctd.contactdata;
ctdtl.ocCTAddress = ctadd;
}
}
eiex.ocFullName = ctfullname;
}
}
eiex.ocClientTaxonomy = cltax;
eiex.ocContactDetails = ctdtl;
ei.Add(eiex);
}
Hope this helps and fit in your requirements.
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();