Unable to Parsing nested Json file in C# - c#

I have Json format response from a API call and I want to map the data from the response to each varibales.
Json format
{
"success": true,
"data": {
"students": [
{
"Admission_date": "2018-05-01",
"Name": "Sree",
"Branch": "Electronics",
"Semester": "2",
"HOD": "Mahesh",
},
{
"Admission_date": "2018-05-01",
"Name": "Naresh",
"Branch": "Electronics",
"Semester": "2",
"HOD": "Mahesh",
}
],
"remaining": 0
}
}
I have tried to parse the JSON response and then to load the value through for each. But I'm not able to achieve the solution.
JObject jsonparsing1 = JObject.Parse(str4); //str4;- Json value
var token1 = (JArray)jsonparsing1.SelectToken("data");
var token2 = (JArray)jsonparsing1.SelectToken("data[0]Students");
JArray abc = JsonConvert.DeserializeObject<JArray>(token2.ToString());
foreach (var test in abc)
{
String Admission_date=test["Admission_date"];
String Name=test["Name"];
String Branch=test["Branch"];
String Semester=test["Semester"];
String HOD=test["HOD"];
String remaining=test["remaining"];
}
Expected result
String Admission_date=Admission_date
String Name=Name
String Branch=Branch
String Semester=Semester
String HOD=HOD
String remaining=remaining
Could anyone please help me on this?

I think you can use this sample:
public class JsonData
{
public bool success { get; set; }
public Data data { get; set; }
}
public class Data
{
public Data()
{
this.students = new List<Student>();
}
public List<Student> students { get; set; }
public int remaining { get; set; }
}
public class Student
{
public string Admission_date { get; set; }
public string Name { get; set; }
public string Branch { get; set; }
public string Semester { get; set; }
public string HOD { get; set; }
}
And then:
JsonData abc = JsonConvert.DeserializeObject<JsonData>(token2.ToString());

I will do this way!
public class Student
{
public string Admission_date { get; set; }
public string Name { get; set; }
public string Branch { get; set; }
public string Semester { get; set; }
public string HOD { get; set; }
}
public class Data
{
public List<Student> students { get; set; }
public int remaining { get; set; }
}
public class RootObject
{
public bool success { get; set; }
public Data data { get; set; }
}
and in C# Code Just use only below line:
var obj = JsonConvert.DeserializeObject<RootObject>("{ \"success\": true,\"data\": {\"students\": [{ \"Admission_date\": \"2018-05-01\",\"Name\": \"Sree\",\"Branch\":\"Electronics\",\"Semester\": \"2\",\"HOD\": \"Mahesh\",}],\"remaining\": 0}}");
use
foreach(var item in obj.data.students)
{
// Access Admission_date etc.
string name = item.Name;
}
dotnetfiddle

Related

Problem Deserializing JSON to objects in C#

I have the below response from the API in a console application written in C#:
{
"d": {
"results": [
{
"__metadata": {
"id": "123",
"uri": "456",
"type": "789"
},
"PERNR": "1",
"USRID": "2"
},
{
"__metadata": {
"id": "159",
"uri": "951",
"type": "753"
},
"PERNR": "4",
"USRID": "6"
}
]
}
}
And used the below code to deserialize:
public class d
{
public results results { get; set; }
}
public class results
{
public string PERNR { get; set; }
public string USRID { get; set; }
public __metadata __metadata { get; set; }
}
public class __metadata
{
public string id { get; set;}
public string uri { get; set; }
public string type { get; set; }
}
var serilizer = new JavaScriptSerializer();
d output = serilizer.Deserialize<d>(response.Content);
But the result is null. Is there any problem in the definition of the classes?
The properties should start with a capital letter, to match the case of the properties in the JSON response. Change the class definitions as follows:
public class D
{
public Results[] results { get; set; }
}
public class Results
{
public string PERNR { get; set; }
public string USRID { get; set; }
public Metadata __metadata { get; set; }
}
public class Metadata
{
public string id { get; set;}
public string uri { get; set; }
public string type { get; set; }
}
Change deserialize line to:
var serilizer = new JavaScriptSerializer();
D output = serilizer.Deserialize<D>(response.Content);
The issue is results is an array in your json, where in your class, it is an object. Change it to
public class d
{
public Result[] results { get; set; }
}
If you use a JSON to C# converter like json2csharp or Visual Studio's Paste JSON As Classes you'll get :
public class Root
{
public D d { get; set; }
}
public class D
{
public List<Result> results { get; set; }
}
public class Metadata
{
public string id { get; set; }
public string uri { get; set; }
public string type { get; set; }
}
public class Result
{
public Metadata __metadata { get; set; }
public string PERNR { get; set; }
public string USRID { get; set; }
}
There are two important differences :
The JSON document contains a root element with an attribute named d, not a D object
D.results is a collection of Result objects, not a single object

How to map json key to a class property

I have a json response like below
{
"Robert": [
{
"id": "123",
"class": "7th",
"lastname": "johnson"
}
],
"William": [
{
"id": "124",
"class": "7th",
"lastname": "parker"
}
]
}
i want to map it to c# class.
Using online converter i get below structure
public class Robert {
public string id { get; set; }
public string class { get; set; }
public string lastname { get; set; }
}
public class William {
public string id { get; set; }
public string class { get; set; }
public string lastname { get; set; }
}
public class Application {
public IList<Robert> Robert { get; set; }
public IList<William> William { get; set; }
}
instead i would like to map the student name as one of the class property say .. "Name"
public class Student{
public string Name{ get; set; } //Robert is mapped to this
public string id { get; set; }
public string class { get; set; }
public string lastname { get; set; }
}
How can i do this ?
You can read above JSON like this
var responseObject = JsonConvert.DeserializeObject<JObject>(responseStream); //Deserialized JSON to type of JObject
var robert = responseObject["Robert"].ToObject<Student>();
your student class should be like this
public class Student{
public string id { get; set; }
public string class { get; set; }
public string lastname { get; set; }
}
with this, you can read the id, class, lastname of Robert.
just an option to read JSON responses like yours.
class Program
{
public class Student
{
public string Name { get; set; } //Robert is mapped to this
public string id { get; set; }
[JsonProperty("class")]
public string _class { get; set; }
public string lastname { get; set; }
}
static void Main(string[] args)
{
var responseStream = #"{""Robert"": [{""id"": ""123"",""class"": ""7th"",""lastname"": ""johnson""}],""William"": [{""id"": ""123"",""class"": ""7th"",""lastname"": ""johnson""}]}";
var responseObject = JsonConvert.DeserializeObject<JObject>(responseStream); //Deserialized JSON to type of JObject
var list = responseObject.Properties();
var students = new List<Student>();
foreach (var item in list)
{
var s = responseObject[item.Name].ToObject<List<Student>>();
s.ForEach(x => x.Name = item.Name);
students.AddRange(s);
}
}
}
Deserialize the json to Dictionary<string, List<Student>> and use Linq to convert to the desired object
var strJSON = File.ReadAllText("json1.json");
var objStudents = JsonConvert.DeserializeObject<Dictionary<string, List<Student>>>(strJSON);
var result = objStudents.Select(x => new Student
{
Name = x.Key,
id = x.Value[0].id,
studentclass = x.Value[0].studentclass,
lastname = x.Value[0].lastname,
}).ToList();

Deserialize complex JSON at c#

I get this object from API
{
"addedAt": 1573172075745,
"vid": 12590024,
"canonical-vid": 12590024,
"merged-vids": [],
"portal-id": 62515,
"is-contact": true,
"profile-token": "AO_T-mOW3t21rXoDQIhBpPulGUoTyxQKLbBxaHrS2P3MsXjF4qFJ9BIvIgkVDpeha5P3GHujF8FOP-0XFRndATAU_YogQKRBTDddOFx8s_DITNLUrnfU07QCwW61HUPygEAyDeNG6N8d",
"profile-url": "https://app.hubspot.com/contacts/62515/contact/12590024",
"properties": {
"firstname": {
"value": "Matt"
},
"lastmodifieddate": {
"value": "1573172075745"
},
"company": {
"value": "HubSpot"
},
"lastname": {
"value": "Schnitt"
}
}
}
and try to fill this model
class UserProperties
{
public string firstname { get; set; }
public DateTime lastmodifieddate { get; set; }
public string company { get; set; }
public string lastname { get; set; }
}
class UserForDeserialize
{
public int vid { get; set; }
public List<UserProperties> properties { get; set; }
}
with this code
class ApiControl
{
public void GetAllUsers()
{
using (var client = new WebClient())
{
client.Headers.Add("Content-Type:application/json");
client.Headers.Add("Accept:application/json");
var result = client.DownloadString("https://api.hubapi.com/contacts/v1/lists/recently_updated/contacts/recent?hapikey=demo&count=2");
JavaScriptSerializer jsonSerializer = new JavaScriptSerializer();
dynamic dobj = jsonSerializer.Deserialize<dynamic>(result);
var obf = dobj["contacts"];
foreach (var item in obf)
{
var exampleModel = jsonSerializer.Deserialize<UserForDeserialize>(json);
}
Console.Read();
}
}
}
Id filled good but list of Properties have all null properties.
Maybe it's because of "value" field inside each property but I can't find good solution for this.
What can I try to deserialize JSON?
Your class should be like this.
public class Root
{
public long addedAt { get; set; }
public int vid { get; set; }
public int canonicalvid { get; set; }
public object[] mergedvids { get; set; }
public int portalid { get; set; }
public bool iscontact { get; set; }
public string profiletoken { get; set; }
public string profileurl { get; set; }
public Properties properties { get; set; }
}
public class Properties
{
public Firstname firstname { get; set; }
public Lastmodifieddate lastmodifieddate { get; set; }
public Company company { get; set; }
public Lastname lastname { get; set; }
}
public class Firstname
{
public string value { get; set; }
}
public class Lastmodifieddate
{
public string value { get; set; }
}
public class Company
{
public string value { get; set; }
}
public class Lastname
{
public string value { get; set; }
}
and then deserialise using this.
JavaScriptSerializer js = new JavaScriptSerializer();
Root rootObject = js.Deserialize<Root>(result );
Looks like the model generated from json is incorrect. I have used json2csharp to convert your json and the model looked like below
public class Firstname
{
public string value { get; set; }
}
public class Lastmodifieddate
{
public string value { get; set; }
}
public class Company
{
public string value { get; set; }
}
public class Lastname
{
public string value { get; set; }
}
public class Properties
{
public Firstname firstname { get; set; }
public Lastmodifieddate lastmodifieddate { get; set; }
public Company company { get; set; }
public Lastname lastname { get; set; }
}
public class UserForDeserialize
{
public int vid { get; set; }
public Properties properties { get; set; }
}
After this, I am able to read the properties
using (StreamReader r = new StreamReader(filename))
{
string json = r.ReadToEnd();
var obj = JsonConvert.DeserializeObject<UserForDeserialize>(json);
Console.WriteLine(obj.properties.firstname);
}
Change the type of your properties in 'UserProperties' for another class which contains:
public string value { get; set; }
Because you're missing that property inside your UserProperties object, I think that's the principal problem you're dealing with.

How to read sections of JSON document?

I have a JSON document and I want to access the details of the STATUS SECTION but it keeps returning null.
JSON Data is as shown:
{
"results":[
{
"messageId":"15712480583306574",
"to":"",
"from":"TestServer",
"sentAt":"2019-10-16T17:47:38.368+0000",
"doneAt":"2019-10-16T17:47:38.370+0000",
"smsCount":1,
"mccMnc":"null",
"price":{
"pricePerMessage":0.0,
"currency":"USD"
},
"status":{
"groupId":5,
"groupName":"REJECTED",
"id":8,
"name":"REJECTED_PREFIX_MISSING",
"description":"Number prefix missing"
},
"error":{
"groupId":0,
"groupName":"OK",
"id":0,
"name":"NO_ERROR",
"description":"No Error",
"permanent":false
}
}
]
}
C# Code is:
string JsonData = response.Content.ToString();
dynamic results = JsonConvert.DeserializeObject<dynamic>(JsonData);
var statuses = results.status;
foreach(var stat in statuses) {
string groupname = stat.groupName.Value;
string name = stat.name.Value;
string description = stat.description.Value;
}
It keeps returning null, How can I access these members? I am using Newtonsoft.
If you want to access the status object property you need to rewrite your whole code.
string JsonData = response.Content.ToString();
var input = JObject.Parse(str);
var results = input["results"].Children();
var status = results.First()["status"];
string groupname = status["groupName"].ToString();
string name = status["name"].ToString();
string description = status["description"].ToString();
Console.WriteLine(groupname);
Console.WriteLine(name);
Console.WriteLine(description);
The result in Console
REJECTED
REJECTED_PREFIX_MISSING
Number prefix missing
But I would rather use concrete class. You need to create multiple classes. Here is good example.
public class Envelope
{
public List<Item> Results { get; set; }
}
public class Item
{
public Status Status { get; set; }
}
public class Status
{
public int GroupId { get; set; }
public string GroupName { get; set; }
public int Id { get; set; }
public string Name { get; set; }
public string Description { get; set; }
}
After that the usage is much simpler.
string JsonData = response.Content.ToString();
MyEnvelope envelope = JsonConvert.DeserializeObject<MyEnvelope>(JsonData);
var status = envelope.results[0].status;
Console.WriteLine(status.GroupName);
Console.WriteLine(status.Name);
Console.WriteLine(status.Description);
Finest Option: Create A model for the JSON.
public class Price
{
public double pricePerMessage { get; set; }
public string currency { get; set; }
}
public class Status
{
public int groupId { get; set; }
public string groupName { get; set; }
public int id { get; set; }
public string name { get; set; }
public string description { get; set; }
}
public class Error
{
public int groupId { get; set; }
public string groupName { get; set; }
public int id { get; set; }
public string name { get; set; }
public string description { get; set; }
public bool permanent { get; set; }
}
public class Result
{
public string messageId { get; set; }
public string to { get; set; }
public string from { get; set; }
public DateTime sentAt { get; set; }
public DateTime doneAt { get; set; }
public int smsCount { get; set; }
public string mccMnc { get; set; }
public Price price { get; set; }
public Status status { get; set; }
public Error error { get; set; }
}
public class RootObject
{
public List<Result> results { get; set; }
}
Then do RootObject results = JsonConvert.DeserializeObject<RootObject>(JsonData);
Fair Option: Get the exact JToken you want.
using System;
using Newtonsoft.Json;
using Newtonsoft.Json.Serialization;
using Newtonsoft.Json.Linq;
public class Program
{
public static void Main()
{
string jsonData = "{\"results\":[{\"messageId\":\"15712480583306574\",\"to\":\"\",\"from\":\"TestServer\",\"sentAt\":\"2019-10-16T17:47:38.368+0000\",\"doneAt\":\"2019-10-16T17:47:38.370+0000\",\"smsCount\":1,\"mccMnc\":\"null\",\"price\":{\"pricePerMessage\":0.0,\"currency\":\"USD\"},\"status\":{\"groupId\":5,\"groupName\":\"REJECTED\",\"id\":8,\"name\":\"REJECTED_PREFIX_MISSING\",\"description\":\"Number prefix missing\"},\"error\":{\"groupId\":0,\"groupName\":\"OK\",\"id\":0,\"name\":\"NO_ERROR\",\"description\":\"No Error\",\"permanent\":false}}]}";
JObject jObject = JObject.Parse(jsonData);
Console.WriteLine(jObject.SelectToken("results[0].status"));
}
}

How can I deserialize JSON into this POCO class?

ERROR:
Cannot implicitly convert type 'UserItem' to 'RootObject'
How can I deserialize JSON into this POCO class?
I'm simply trying to deserilize json data into C# custom poco class as shown below and here is what i have done so far;
public static UserItem DownloadJSONString(string urlJson)
{
using (WebClient wc = new WebClient())
{
var json = wc.DownloadString(urlJson);
UserItem userItems = JsonConvert.DeserializeObject<RootObject>(json);
return userItems;
}
}
I'm kind of stuck here
here my Json:
{
"meta":
{
"status":200,
"resultSet":
{
"id":"05"
},
"pagination":
{
"count":2,
"pageNum":1,
"pageSize":2
}
},
"results":
{
"id":0,
"name":
"title",
"items":
[
{
"id":0,
"name":"English",
"title":"English",
},
{
"id":0,
"name":"Spanish",
"title":"Spanish;",
}
]
}
}
here is my json object (generate from json to c# class)
public class ResultSet
{
public string id { get; set; }
}
public class Pagination
{
public int count { get; set; }
public int pageNum { get; set; }
public int pageSize { get; set; }
}
public class Meta
{
public int status { get; set; }
public ResultSet resultSet { get; set; }
public Pagination pagination { get; set; }
}
public class Item
{
public int id { get; set; }
public string name { get; set; }
public string title { get; set; }
}
public class Results
{
public int id { get; set; }
public string name { get; set; }
public List<Item> items { get; set; }
}
public class RootObject
{
public Meta meta { get; set; }
public Results results { get; set; }
}
Here is my simple UserItem POCO class
public class UserItem
{
public int id { get; set; }
public string name { get; set; }
public string title { get; set; }
}
Here you go:
var root = JsonConvert.DeserializeObject<RootObject>(json);
var userItem = root.results.items
.Select(i => new UserItem
{
id = i.id,
name = i.name,
title = i.title
}).FirstOrDefault();
return userItem;
As you already know, you can't just convert the Item class into a UserItem, but you can build one. One thing to note here is that obviously if you only want to return one you'll have to just grab one. Here I've grabbed the first or default. The default would be null if the list were empty for example.

Categories

Resources