How can I deserialize JSON into this POCO class? - c#

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.

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

Deserializing JSON into C# Object

I am trying to deserialize a json object into c# object and list the Itinerary items.
Here is my json object:
{
"data": {
"Itineraries": [
{
"isDomestic": false,
"departureAirport": "IKA",
"arrivalAirport": "IST"
},
{
"isDomestic": false,
"departureAirport": "IST",
"arrivalAirport": "LAX"
}
]
}
}
here is my c# classes that I use
public class Data
{
public List<itineraries> itineraries { get; set; } = new List<itineraries>();
}
public class itineraries
{
public bool isDomestic { get; set; }
public string departureAirport { get; set; }
public string arrivalAirport { get; set; }
}
here is the code that I use to deserialize
Data availableData= JsonSerializer.Deserialize<Data>(json);
foreach (var item in availableData.itineraries){
Console.WriteLine($"departureAirport:{item.departureAirport}");
}
But I could not list the itineraries.
try this classes
public class Itinerary
{
public bool isDomestic { get; set; }
public string departureAirport { get; set; }
public string arrivalAirport { get; set; }
}
public class Data
{
public List<Itinerary> Itineraries { get; set; }
}
public class Root
{
public Data data { get; set; }
}
and code
var availableData= JsonSerializer.Deserialize<Root>(json);
foreach (var item in availableData.data.Itineraries)
{
Console.WriteLine($"departureAirport:{item.departureAirport}");
}
first, you have to install Newtonsoft.Json from NuGet Manager
then use these classes instead of yours
public class Itinerary
{
public bool isDomestic { get; set; }
public string departureAirport { get; set; }
public string arrivalAirport { get; set; }
}
public class Data
{
public List<Itinerary> Itineraries { get; set; }
}
public class Root
{
public Data data { get; set; }
}
the convert code is
var root = JsonConvert.DeserializeObject<Root>(json);

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.

Unable to Parsing nested Json file in 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

How to make an c# object from json

I get the following response from a webservice:
{
"data":{
"foo.hugo.info": {
"path": "logon.cgi",
"minVersion": 1,
"maxVersion": 2
},
"foo.Fritz.Task": {
"path": "Fritz/process.cgi",
"minVersion": 1,
"maxVersion": 1
}
},
"success": true
}
How must the json-object look like to deserialize this?
Or is there another way to get the values of the properties?
With the JSON.NET library it's pretty trivial:
public class Root
{
public Dictionary<string, Data> Data { get; set; }
public bool Success { get; set; }
}
public class Data
{
public string Path { get; set; }
public int MinVersion { get; set; }
public int MaxVersion { get; set; }
}
and then:
string json =
#"{
""data"":{
""foo.hugo.info"": {
""path"": ""logon.cgi"",
""minVersion"": 1,
""maxVersion"": 2
},
""foo.Fritz.Task"": {
""path"": ""Fritz/process.cgi"",
""minVersion"": 1,
""maxVersion"": 1
}
},
""success"": true
}";
Root root = JsonConvert.DeserializeObject<Root>(json);
In this example I have used a Dictionary<string, Data> object to model the 2 complex keys (foo.hugo.info and foo.Fritz.Task) because they contain names that cannot be used in a .NET member.
If you're using VS2012 or above you can do the following:
Edit > Paste Special > Paste JSON As Classes
With your example, this results in:
public class Rootobject
{
public Data data { get; set; }
public bool success { get; set; }
}
public class Data
{
public FooHugoInfo foohugoinfo { get; set; }
public FooFritzTask fooFritzTask { get; set; }
}
public class FooHugoInfo
{
public string path { get; set; }
public int minVersion { get; set; }
public int maxVersion { get; set; }
}
public class FooFritzTask
{
public string path { get; set; }
public int minVersion { get; set; }
public int maxVersion { get; set; }
}
Check out this site: http://json2csharp.com/
Paste in the json string and it will generate classes for you. I usually use this in hand with JSON.NET to deserialize an instance of the Root Object.
You can use DataContractJsonSerializer
[DataContract]
public class DetailedData
{
[DataMember(Name="path")]
public string Path { get; set; }
[DataMember(Name = "minVersion")]
public int MinVersion { get; set; }
[DataMember(Name = "maxVersion")]
public int MaxVersion { get; set; }
}
[DataContract]
public class Data
{
[DataMember(Name = "foo.hugo.info")]
public DetailedData Info { get; set; }
[DataMember(Name = "foo.Fritz.Task")]
public DetailedData Task { get; set; }
}
[DataContract]
public class RootObject
{
[DataMember(Name = "data")]
public Data Data { get; set; }
[DataMember(Name = "success")]
public bool Success { get; set; }
}
static void Main(string[] args)
{
string json = "...";
DataContractJsonSerializer js = new DataContractJsonSerializer(typeof(RootObject));
RootObject obj = (RootObject)js.ReadObject(new MemoryStream(Encoding.Unicode.GetBytes(json)));
Console.WriteLine(obj.Data.Task.MaxVersion);
}
Edit: same class for Info and Task

Categories

Resources