Parsing Array of objects JSON in C# - c#

My JSON Input is below. Sry it is too long
{
"status":{
"success":[
{
"User":{
"id":"1377",
"username":"Dr.Hema Sathish",
"username_url":"dr-hema-sathish",
"firstname":null,
"lastname":null,
"email":"madurai#sancheclinic.com",
"password":"6c7ab07e828828206e3d7c56c3c35cfd383960cd",
"user_level":"doctor"
},
"Speciality":{
"id":"2",
"name":"Dermatology(Skin Specialist)",
"slug":"dermatology-skin-specialist",
"image":"1438693213.png",
"status":"1",
"created":"2015-07-08 03:35:57",
"modified":"2016-09-13 13:58:36"
}
}
]
}
}
I have downloaded JSON String from URL Successfully.
static void main
{
using (var webClient = new System.Net.WebClient())
{
string json = webClient.DownloadString("http://myURL/");
Console.WriteLine(json.ToString());
}
}
Now I have to get User and Speciality objects. Its confusing to parse Array of Objects Json. How to parse it?
I have tried Deserialization. But it does not work.
How to parse it?

Your json is invalid...here is correct json
{
"status": {
"success": [{
"User": {
"id": "1377",
"username": "Dr.Hema Sathish"
},
"Speciality": {
"id": "2",
"name": "Dermatology(Skin Specialist)"
}
},
{
"User": {
"id": "1390",
"username": "Dr.Nichita Balaji"
},
"Speciality": {
"id": "2",
"name": "Dermatology(Skin Specialist)"
}
}
]
}
}
You can create below classes to deserialize it using Newtonsoft
public class User
{
public string id { get; set; }
public string username { get; set; }
}
public class Speciality
{
public string id { get; set; }
public string name { get; set; }
}
public class Success
{
public User User { get; set; }
public Speciality Speciality { get; set; }
}
public class Status
{
public List<Success> success { get; set; }
}
public class RootObject
{
public Status status { get; set; }
}
Here is the code to deserialize it
string json =
" {\r\n \t\"status\": {\r\n \t\t\"success\": [{\r\n \t\t\t\t\"User\": {\r\n \t\t\t\t\t\"id\": \"1377\",\r\n \t\t\t\t\t\"username\": \"Dr.Hema Sathish\"\r\n \t\t\t\t},\r\n \t\t\t\t\"Speciality\": {\r\n \t\t\t\t\t\"id\": \"2\",\r\n \t\t\t\t\t\"name\": \"Dermatology(Skin Specialist)\"\r\n \t\t\t\t}\r\n \t\t\t},\r\n \t\t\t{\r\n \t\t\t\t\"User\": {\r\n \t\t\t\t\t\"id\": \"1390\",\r\n \t\t\t\t\t\"username\": \"Dr.Nichita Balaji\"\r\n \t\t\t\t},\r\n \t\t\t\t\"Speciality\": {\r\n \t\t\t\t\t\"id\": \"2\",\r\n \t\t\t\t\t\"name\": \"Dermatology(Skin Specialist)\"\r\n \t\t\t\t}\r\n\r\n \t\t\t}\r\n \t\t]\r\n \t}\r\n }";
RootObject rootObject = JsonConvert.DeserializeObject<RootObject>(json);
var successes = rootObject.status.success;
var specialityObjects = successes.Select(success => success.Speciality).ToList();
var users = successes.Select(success => success.User).ToList();
Console.WriteLine(users[0].id + " " + users[0].username);
Console.WriteLine(users[1].id + " " + users[1].username);
Console.WriteLine(specialityObjects[0].id + " " + specialityObjects[0].name);
Console.WriteLine(specialityObjects[1].id + " " + specialityObjects[1].name);
Console.ReadLine();
//OUTPUT
1377 Dr.Hema Sathish
1390 Dr.Nichita Balaji
2 Dermatology(Skin Specialist)
2 Dermatology(Skin Specialist)

You have to create classes according to JSON data set :
public class User
{
public int Id { get; set; }
public string Username { get; set; }
public string Firstname { get; set; }
public string Lastname { get; set; }
}
public class Speciality
{
public int Id { get; set; }
public string Name { get; set; }
}
Then, you should be able to Deserialize using JSON .NET library
string json = webClient.DownloadString("http://myURL/");
User u = JsonConvert.DeserializeObject<User>(json);
There may be other library available, nonetheless this one is working fine (and is available as NuGET package).
Please note this is only a sample, your code will miss several classes to properly parse your JSON (Status class, etc.).

Related

C#, JSON.net Loop through and store Jobject objects

New to both C# and to using JSON. Trying to make something that works with some JSON from a web API in the following format. Would like to loop through and store the secondUser_id and and the status for later use.
{
"user_list": [
{
"user_id": "12345678910",
"secondUser_id": "5428631729616515697",
"member_since": "1521326679",
"member_since_date": "2018-03-32",
"function": "test",
"rank_int": "1",
"status": "0"
},
{
"user_id": "11345638910",
"secondUser_id": "5428631729616515697",
"member_since": "1521326679",
"member_since_date": "2018-03-32",
"function": "test",
"rank_int": "1",
"status": "0"
},
{
"user_id": "13452578910",
"secondUser_id": "12390478910",
"member_since": "12316578910",
"member_since_date": "2018-03-32",
"function": "test",
"rank_int": "1",
"status": "0"
}
],
"returned": 3
}
string jsonUrl = GetJSON("url");
JObject UsersJObject = JObject.Parse(jsonUrl);
JToken user = UsersJObject["user_list"].First["secondUser_id"];
Console.WriteLine("User ID: " + user);
This will get the first entry but I'm not sure what to use for a enumerator?
try something like this:
foreach (var obj in UsersJObject["user_list"] as JArray)
{
Console.WriteLine(obj["secondUser_id"]);
}
You can iterate over elements of a JArray, and user_list will be of that type, cast it and you can iterate it in a foreach loop.
I will recommend you to use JsonConvert.DeserializeObject<T>.
This can help you to use objects easily
public class UserList
{
public string user_id { get; set; }
public string secondUser_id { get; set; }
public string member_since { get; set; }
public string member_since_date { get; set; }
public string function { get; set; }
public string rank_int { get; set; }
public string status { get; set; }
}
public class JsonData
{
public List<UserList> user_list { get; set; }
public int returned { get; set; }
}
Use like this.
string jsonUrl = GetJSON("url");
JsonData UsersJObject = JsonConvert.DeserializeObject<JsonData>(jsonUrl);
foreach (var obj in UsersJObject.user_list)
{
Console.WriteLine(obj.secondUser_id);
}

Deserialize JSON object xamarin C#

I am getting the following error in Xamarin cross platform while deserializing the JSON Object. I have tried to do it with dictionary. But, everything gives me the same exception.
Newtonsoft.Json.JsonSerializationException: Cannot deserialize the current JSON object (e.g. {\"name\":\"value\"}) into type 'System.Collections.Generic.List`1[NBStudents.Models.jsonobjectclass+User]' because the type requires a JSON array (e.g. [1,2,3]) to deserialize correctly.
To fix this error either change the JSON to a JSON array (e.g. [1,2,3]) or change the deserialized type so that it is a normal .NET type (e.g. not a primitive type like integer, not a collection type like an array or List<T>) that can be deserialized from a JSON object. JsonObjectAttribute can also be added to the type to force it to deserialize from a JSON object.Path 'data.name', line 4, position 11.
My JSON Object Class:
public class jsonobjectclass
{
public class User
{
public string name { get; set; }
public string email { get; set; }
public string phone { get; set; }
public string current_group { get; set; }
public List<UserGroups> user_groups { get; set; }
}
public class UserGroups
{
[JsonProperty("10")]
public string Student { get; set; }
[JsonProperty("15")]
public string Tutor { get; set; }
[JsonProperty("11")]
public string Parent { get; set; }
}
public class Token
{
public string access_token { get; set; }
public int expires_in { get; set; }
public string token_type { get; set; }
public string scope { get; set; }
public string refresh_token { get; set; }
public string error { get; set; }
}
public class UserResponse
{
public string msg { get; set; }
public List<User> data { get; set; }
public bool error { get; set; }
}
}
My Code to Deserialize JSON:
public static async Task<jsonobjectclass.UserResponse> UserRetrievalTask(string token, string apiUrl)
{
var jsonObject = new jsonobjectclass.UserResponse();
string readHttpResponse;
using (var httpClient = new HttpClient())
{
using (var httpRequestMessage = new HttpRequestMessage(HttpMethod.Get, apiUrl))
{
httpRequestMessage.Headers.Add("Authorization", "Bearer " + token);
using (var httpResponse = await httpClient.SendAsync(httpRequestMessage).ConfigureAwait(false))
{
readHttpResponse = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
var jObject = JObject.Parse(readHttpResponse);
try
{
jsonObject = JsonConvert.DeserializeObject<jsonobjectclass.UserResponse>(jObject.ToString());
}
catch(Exception ex)
{
string excep = ex.ToString();
readHttpResponse = excep;
}
}
}
}
return jsonObject;
}
My JSON String:
{{
"msg": null,
"data": {
"name": "geoit",
"email": "rokesh#geoit.in",
"phone": null,
"current_group": "11",
"user_groups": {
"11": "Parent"
}
},
"error": false
}}
Please Help me to solve this.
Thanks,
Rokesh
You have mismatch between the string and the object you are trying to deserialize into. The data object is not an array and there is an additional nested object which is not named in the JSON separately containing the msg field and the user data, but the error field is not part of that object:
As the comments have pointed out the JSON is not valid as is, so if you have control of the source I would fix that.
If not you could implement a reader and parse it as token by token, something like this:
using (var response = await client.GetAsync(_url, HttpCompletionOption.ResponseHeadersRead))
using (var stream = await response.Content.ReadAsStreamAsync())
using (var streamReader = new StreamReader(stream))
using (var reader = new JsonTextReader(streamReader))
{
var serializer = new JsonSerializer();
while (reader.Read())
{
switch (reader.TokenType)
{
case JsonToken.Start:
// code to handle it
break;
case JsonToken.PropertyName:
// code to handle it
break;
// more options
}
}
}
although this approach is more fragile. You can take a look at The JSON.Net JsonToken docs for more info.
Based on your comment and using https://jsonlint.com/ the response string
"{\"msg\":null,\"data\":{\"name\":\"geoit\",\"email\":\"roke‌​sh#geoit.in\",\"phon‌​e\":null,\"current_g‌​roup\":\"11\",\"user‌​_groups\":{\"11\":\"‌​Parent\"}},\"error\"‌​:false}"
is actually valid JSON, but the object is a little bizarre. I think it looks something like this in C#
public class UserGroup
{
public string 11 { get; set; }
}
public class UserData {
public string name { get; set; }
public string email { get; set; }
public string phone { get; set; }
public string current_group { get; set; }
public UserGroup user_groups { get; set; }
}
public class ResponseObject
{
public string msg { get; set; }
public UserData data { get; set; }
public bool error { get; set; }
}
It should be an array the opening and closing brackets should be square brackets:
[
{ "msg": null,"data":
[ {
"name": "geoit",
"email": "rokesh#geoit.in",
"phone": null,
"current_group": "11",
"user_groups":
[{
"11": "Parent"
}
]
}
],
"error": false
}
]
Also in your code, you dont need var jObject = JObject.Parse(readHttpResponse); since the readHttpResponse is already a JSON string which you can deserialzie into an object.
Aplogies for the misleading answer earlier. The object you need to make array is the 'data' property of the response JSON. You have to get it from the server side as your Domainmodal List<User>. You should get a better understanding from this fiddle
readHttpResponse can be
{
"msg": null,
"data": [{
"name": "geoit",
"email": "rokesh#geoit.in",
"phone": null,
"current_group": "11",
"user_groups": {
"11": "Parent"
}
}],
"error": false
}
and
readHttpResponse.data needs to be array
[{
"name": "geoit",
"email": "rokesh#geoit.in",
"phone": null,
"current_group": "11",
"user_groups": {
"11": "Parent"
}
}]

Use Linq or C# to parse Json

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.

windows phone: deserialise and store both json key and value to modal

Hello guyzzzz i want to store both key and value in modal class...below is my json..
{
"Example": [
{
"Invoice": {
"TFDGFF": " 200",
"BF": " 200",
"MD": "10",
"EFM": " 12",
"ATT": "4"
},
"TF": "200"
},
{
"Invoice": {
"DF": " 49",
"DR": " 49",
"KJ": "4",
"LKIH": " 14",
"KJGU": "4"
},
"DF": "49"
}
please tell me how to deserialise this json so that i can store both key as well as value in modal class and how should be the design of modal class ??
public class Invoice
{
public string TF { get; set; }
public string BF { get; set; }
public string MD { get; set; }
public string EFM { get; set; }
public string ATT { get; set; }
public string FPK { get; set; }
}
public class Example
{
public Invoice Invoice { get; set; }
public string TF { get; set; }
}
public class RootObject
{
public List<Example> Example { get; set; }
}
Make use of json2csharp.com
Now make use of newtonsoft package to deserialize your json
var obj = JsonConvert.DeserializeObject<RootObject>(yourstring);
For New JSON
public class RootObject
{
public List<Example> Example { get; set; }
}
public class Example
{
public Dictionary<string, string> Invoice { get; set; }
}
And you call it using
string temp=#" { ""Example"": [ { ""Invoice"": { ""TFDGFF"": ""200"", ""BF"": ""200"", ""MD"": ""10"", ""EFM"": ""12"", ""ATT"": ""4"" }, ""TF"": ""200"" }, { ""Invoice"": { ""DF"": "" 49"", ""DR"": "" 49"", ""KJ"": ""4"", ""LKIH"": "" 14"", ""KJGU"": ""4"" }, ""DF"": ""49"" }]}";
var obj = JsonConvert.DeserializeObject<RootObject>(temp);
For new Question Regarding Bind
for (int i = 0; i < obj.Example.Count(); i++)
{
foreach (KeyValuePair<string, string> pair in obj.Example[i].Invoice)
{
string temp3 = pair.Key;
string temp2 = pair.Value;
}
}

Find a value from the json string in c#

This is my json string :
{"loginAccounts": [
{
"name": "abc",
"accountId": "123456",
"baseUrl": "https://abc.defghi.com/test/t12/remark/123456",
"isDefault": "true",
"userName": "Ceilina James",
"userId": "7c5bat57-850a-5c93-39eb-2015ai9o8822",
"email": "abc#test.com",
"siteDescription": ""
}
]}
I need "baseUrl" value. How to find it in the C# ?
You could use a JSON serializer such as the JavaScriptSerializer class to deserialize this JSON string to a C# class and then extract the required value. For example you could have the following model:
public class SomeModel
{
public LoginAccount[] LoginAccounts { get; set; }
}
public class LoginAccount
{
public string Name { get; set; }
public string AccountId { get; set; }
public string BaseUrl { get; set; }
public string IsDefault { get; set; }
...
}
and then:
string json = "... your JSON string comes here ...";
var serializer = new JavaScriptSerializer();
string json = ...
var model = (SomeModel)serializer.Deserialize(json);
foreach (var account in model.LoginAccounts)
{
string baseUrl = account.BaseUrl;
...
}
Using Json.Net
foreach (var acc in JObject.Parse(json)["loginAccounts"])
{
Console.WriteLine(acc["baseUrl"]);
}

Categories