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();
Related
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
I am attempting to get students from an api and display their information but am having some trouble deserializing some json that I am retrieving. I am using c#
Here is what is being retrieved:
[
{
"firstName": "John",
"lastName: "Smith",
"id": "122386144",
"schoolYear": "Sophmore",
"Links": [
{
"url": "https://github.com/johnsmith",
"comments": "Click to see some of my projects!"
}
],
"GPA": "3.6"
},
{
"firstName": "Jane",
"lastName: "Doe",
"id": "45624523",
"schoolYear": "Junior",
"Links": [
{
"url": "https://linkedin.com/janedoe",
"comments": "Follow me on LinkedIn"
}
],
"GPA": "3.8"
}
]
Here is what I have for my class:
public class Student
{
public string firstName { get; set; }
public string lastName { get; set; }
public int id { get; set; }
public string schoolYear { get; set; }
public string[] Links { get; set; }
}
public class Links
{
public string url { get; set; }
public string comments { get; set; }
}
And Finally my code deserializing the json. I cannot provide the actual url here so the below baseUrl is just a placeholder for this post:
string baseUrl = "https://CodeUniversity.com/"
List<Student> studentList = new List<Student>();
using (var client = new HttpClient())
{
client.BaseAddress = new Uri(baseUrl);
client.DefaultRequestHeaders.Clear();
client.DeafultRequestHeaders.Accept.Add(new
MediaTypeWithQualityHeaderValue("application/json"));
HttpResponseMessage response = await client.GetAsync("api/CS/students");
if (response.IsSuccessStatusCode)
{
var studentResponse = response.Content.ReadAsStringAsync().Result;
studentList = JsonConvert.DeserializeObject<List<Student>(studentResponse);
}
}
When this code runs I receive the following error:
The model item passed into the dictionary is of type
'Newtonsoft.Json.JsonReaderException', but this dictionary requires a
model item of type
'System.Collections.Generic.IEnumerable`1[University.Models.Student]'.
Thanks in advance for the help.
It seems like your Links property of class Student should be type of Links instead of string[].
I would also suggest renaming the Links class to Link
change public string[] Links for public Link[] Links { get; set; }
use this site for convert your json to c# class
your models class
public partial class Student
{
[JsonProperty("firstName")]
public string FirstName { get; set; }
[JsonProperty("lastName")]
public string LastName { get; set; }
[JsonProperty("id")]
public string Id { get; set; }
[JsonProperty("schoolYear")]
public string SchoolYear { get; set; }
[JsonProperty("Links")]
public Link[] Links { get; set; }
[JsonProperty("GPA")]
public string Gpa { get; set; }
}
public partial class Link
{
[JsonProperty("url")]
public Uri Url { get; set; }
[JsonProperty("comments")]
public string Comments { get; set; }
}
and deserialize
var c = JsonConvert.DeserializeObject<Student[]>(studentResponse);
check example here
there is a bug in json, add " to lastName before : . Also fix Links property and add GPA property
public class Student
{
public string firstName { get; set; }
public string lastName { get; set; }
public int id { get; set; }
public string schoolYear { get; set; }
public double GPA { get; set; }
public List<Link> Links { get; set; }
}
public class Link
{
public string url { get; set; }
public string comments { get; set; }
}
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.
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
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.