Json.NET and RESTSharp - Error Converting Value - c#

I have created an API that I am now attempting to access through another application. Even though I am using Newtonsoft.JSON to both serialize and deserialize the JSON, I am encountering a conversion error, with the following InnerException:
{"Could not cast or convert from System.String to System.Collections.Generic.List`1[MidamAPI.Models.ManagerDTO]."}
The following is the snippet that throws the error (in RESTFactory):
public List<T> Execute<T>(String endPoint) where T : new() {
RestClient client = new RestClient(BASE_URL);
IRestRequest req = new RestRequest(endPoint);
req.AddHeader("Authorization", "Bearer " + this._token);
var response = client.Execute(req).Content;
List<T> responseData = JsonConvert.DeserializeObject<List<T>>(response);
return responseData;
}
which is called here:
{
RegisterViewModel vm = new RegisterViewModel();
RESTFactory factory = new RESTFactory((String)Session["bearer"]);
vm.availableManager = factory.Execute<ManagerDTO>("managers");
vm.availableProperties = factory.Execute<PropertyDTO>("locations");
vm.availableTrainers = factory.Execute<TrainerDTO>("trainers");
return View(vm);
}
The information is coming from the following API controller action (in a separate application):
[LocalFilter]
[RoutePrefix("managers")]
public class ManagersController : ApiController
{
UnitOfWork worker = new UnitOfWork();
[Route("")]
public string Get()
{
IEnumerable<ManagerDTO> dtoList = Mapper.Map<List<Manager>, List<ManagerDTO>>(worker.ManagerRepo.Get().ToList());
foreach (ManagerDTO dto in dtoList)
{
Manager manager = worker.ManagerRepo.GetByID(dto.ID);
dto.Stores = (Mapper.Map<IEnumerable<Property>, IEnumerable<PropertyDTO>>(manager.Properties)).ToList();
}
return JsonConvert.SerializeObject(dtoList);
}
The DTOs are the same in both applications:
{
public class ManagerDTO
{
public int ID { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public string Email { get; set; }
public List<PropertyDTO> Stores { get; set; }
}
public class PropertyDTO
{
public int ID;
public string ShortName { get; set; }
public string Street { get; set; }
public string City { get; set; }
public string State { get; set; }
public string Zip { get; set; }
public string Phone { get; set; }
public string Lat { get; set; }
public string Long { get; set; }
public string GooglePlaceID { get; set; }
public string PropertyNumber { get; set; }
public int ManagerID { get; set; }
public int TrainerID { get; set; }
public string ManagerName { get; set; }
public string ManagerEmail { get; set; }
public string TrainerEmail { get; set; }
}
I tried using the json2csharp tool with the response, and everything seems fine to my eyes:
public class Store
{
public int ID { get; set; }
public string ShortName { get; set; }
public string Street { get; set; }
public string City { get; set; }
public string State { get; set; }
public string Zip { get; set; }
public string Phone { get; set; }
public string Lat { get; set; }
public string Long { get; set; }
public string GooglePlaceID { get; set; }
public string PropertyNumber { get; set; }
public int ManagerID { get; set; }
public int TrainerID { get; set; }
public string ManagerName { get; set; }
public string ManagerEmail { get; set; }
public object TrainerEmail { get; set; }
}
public class RootObject
{
public int ID { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public string Email { get; set; }
public List<Store> Stores { get; set; }
}
Any advice would be appreciated.
EDIT:
The RegisterViewModel class
public class RegisterViewModel
{
public RegistrationDTO regModel { get; set; }
public List<ManagerDTO> availableManager { get; set; }
public List<PropertyDTO> availableProperties { get; set; }
public List<TrainerDTO> availableTrainers { get; set; }
}

Make your controller Get() return type
IHttpActionResult
and return
Ok(dtoList);

Related

Consuming web API into Blazor

I'm trying to consume a web API into Blazor but am struggling to extract certain information from the API
using System.Text.Json;
namespace CA3.Song
{
public class SongService : ISongService
{
private readonly HttpClient _httpClient;
const string _baseUrl = "https://genius-song-lyrics1.p.rapidapi.com/";
const string _songEndpoint = "songs/chart?time_period=day&chart_genre=all&per_page=10&page=1";
const string _host = "genius-song-lyrics1.p.rapidapi.com";
const string _key = "{key}";
public SongService(HttpClient httpClient)
{
_httpClient = httpClient;
}
public async Task<List<SongItem>> GetSong()
{
Configure();
var response = await _httpClient.GetAsync(_songEndpoint);
var response_outcome = response.EnsureSuccessStatusCode;
using var stream = await response.Content.ReadAsStreamAsync();
var dto = await JsonSerializer.DeserializeAsync<SongDto>(stream);
return dto.response.chart_items.Select(n => new SongItem { Artist = n.item.primary_artist, Title = n.item.primary_title, ReleaseDate = n.primary_release_date }).ToList().T ;
}
private void Configure()
{
_httpClient.BaseAddress = new Uri(_baseUrl);
_httpClient.DefaultRequestHeaders.Add("X-RapidAPI-Host", _host);
_httpClient.DefaultRequestHeaders.Add("X-Rapid-Key", _key);
}
}
}
The issue is on the return statement using LINQ.
namespace CA3.Song
{
public class SongDto
{
public Meta meta { get; set; }
public Response response { get; set; }
}
public class Meta
{
public int status { get; set; }
}
public class Response
{
public Chart_Items[] chart_items { get; set; }
public int next_page { get; set; }
}
public class Chart_Items
{
public string _type { get; set; }
public string type { get; set; }
public Item item { get; set; }
}
public class Item
{
public string _type { get; set; }
public int annotation_count { get; set; }
public string api_path { get; set; }
public string artist_names { get; set; }
public string full_title { get; set; }
public string header_image_thumbnail_url { get; set; }
public string header_image_url { get; set; }
public int id { get; set; }
public bool instrumental { get; set; }
public int lyrics_owner_id { get; set; }
public string lyrics_state { get; set; }
public int lyrics_updated_at { get; set; }
public string path { get; set; }
public int pyongs_count { get; set; }
public string relationships_index_url { get; set; }
public Release_Date_Components release_date_components { get; set; }
public string release_date_for_display { get; set; }
public string song_art_image_thumbnail_url { get; set; }
public string song_art_image_url { get; set; }
public Stats stats { get; set; }
public string title { get; set; }
public string title_with_featured { get; set; }
public int updated_by_human_at { get; set; }
public string url { get; set; }
public Featured_Artists[] featured_artists { get; set; }
public Primary_Artist primary_artist { get; set; }
}
public class Release_Date_Components
{
public int year { get; set; }
public int month { get; set; }
public int day { get; set; }
}
public class Stats
{
public int unreviewed_annotations { get; set; }
public int concurrents { get; set; }
public bool hot { get; set; }
public int pageviews { get; set; }
}
public class Primary_Artist
{
public string _type { get; set; }
public string api_path { get; set; }
public string header_image_url { get; set; }
public int id { get; set; }
public string image_url { get; set; }
public string index_character { get; set; }
public bool is_meme_verified { get; set; }
public bool is_verified { get; set; }
public string name { get; set; }
public string slug { get; set; }
public string url { get; set; }
public int iq { get; set; }
}
public class Featured_Artists
{
public string _type { get; set; }
public string api_path { get; set; }
public string header_image_url { get; set; }
public int id { get; set; }
public string image_url { get; set; }
public string index_character { get; set; }
public bool is_meme_verified { get; set; }
public bool is_verified { get; set; }
public string name { get; set; }
public string slug { get; set; }
public string url { get; set; }
public int iq { get; set; }
}
}
Above is the JSON file and I'm trying to extract the artist name, song title and release date from Item but it isn't in a list so I'm trying to find a way to extract this info using LINQ. Any help would be greatly appreciated !
I think you misinterpreted the declaration of the JSON. They are stored in an array Chart_Items[] chart_items thus you may use linq.
There are many ways to do this, I took advantage of named tuples in modern C# paired with linq.
Response r = new Response();//some resonse from api
var results = r.chart_items.Select(i => (i.item.artist_names, i.item.title, i.item.release_date_components)).ToList();
foreach(var result in results)
{
string artist_names = result.artist_names;
string title = result.title;
Release_Date_Components release_date_components = result.release_date_components;
}

Cannot deserialize the current JSON in C#

I faced the problem: Cannot deserialize the current JSON object.
As follows:
public List<Track> Tracks { get; set; }
public async Task<List<Track>> GetTracking()
{
using (var httpClient = new HttpClient())
{
using (var requests = new HttpRequestMessage(new HttpMethod("GET"), "urlxxxxxxxx..."))
{
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
requests.Headers.TryAddWithoutValidation("accept", "application/json");
var response = await httpClient.SendAsync(requests);
using (HttpContent content = response.Content)
{
var jsonStr = content.ReadAsStringAsync().GetAwaiter().GetResult();
var res = JsonConvert.DeserializeObject<List<Track>>(jsonStr); //Get Error**
Tracks = res;
}
}
}
return Tracks;
}
Model Class
public class Track
{
public List<Events> events { get; set; }
}
public class Events
{
public string eventID { get; set; }
public string eventType { get; set; }
public string eventDateTime { get; set; }
public string eventCreatedDateTime { get; set; }
public string eventClassifierCode { get; set; }
public string transportEventTypeCode { get; set; }
public string documentID { get; set; }
public string shipmentEventTypeCode { get; set; }
public List<DocumentReferences> documentReferences { get; set; }
public TransportCall transportCall { get; set; }
}
public class DocumentReferencesMearsk
{
public string documentReferenceType { get; set; }
public string documentReferenceValue { get; set; }
}
public class TransportCallMaersk
{
public string transportCallID { get; set; }
public string carrierServiceCode { get; set; }
public string exportVoyageNumber { get; set; }
public string importVoyageNumber { get; set; }
public int transportCallSequenceNumber { get; set; }
public string UNLocationCode { get; set; }
public string facilityCode { get; set; }
public string facilityCodeListProvider { get; set; }
public string facilityTypeCode { get; set; }
public string otherFacility { get; set; }
public string modeOfTransport { get; set; }
public LocationMearsk location { get; set; }
public VesselMearsk vessel { get; set; }
}
My input data:
https://drive.google.com/file/d/12g0nHkHlmbU4Af8crHlzKXD_ERIZdCyH/view?usp=sharing
As in my description. I get the error: I get the error: Newtonsoft.Json.JsonSerializationException: 'Cannot deserialize the current JSON object (e.g. {"name":"value"}) into type 'System.Collections.Generic.List`1[XX. Models.Track]' because the type requires a JSON array (e.g. [1,2,3]) to deserialize correctly.
Even though I declared: public List events { get; set; }
Is the problem I have misunderstood the format of DeserializeObject. Looking forward to everyone's help. Thank
you have an object, not an array
var res = JsonConvert.DeserializeObject<Track>(jsonStr);
and fix class
public class Events
{
....
public List<DocumentReferencesMearsk> documentReferences { get; set; }
public TransportCallMaersk transportCall { get; set; }
}
Your model is incomplete and has typos. Assuming you have the correct versions of them.
You are doing:
var res = JsonConvert.DeserializeObject<List<Track>>(jsonStr);
which should be just:
var res = JsonConvert.DeserializeObject<Track>(jsonStr);
Your json doesn't have an array at the root level.
Full working sample:
void Main()
{
var res = JsonConvert.DeserializeObject<Track>(myJson);
}
public class Track
{
public List<Events> events { get; set; }
}
public class Events
{
public string eventID { get; set; }
public string eventType { get; set; }
public string eventDateTime { get; set; }
public string eventCreatedDateTime { get; set; }
public string eventClassifierCode { get; set; }
public string transportEventTypeCode { get; set; }
public string documentID { get; set; }
public string shipmentEventTypeCode { get; set; }
public List<DocumentReferencesMearsk> documentReferences { get; set; }
public TransportCallMaersk transportCall { get; set; }
}
public class DocumentReferencesMearsk
{
public string documentReferenceType { get; set; }
public string documentReferenceValue { get; set; }
}
public class TransportCallMaersk
{
public string transportCallID { get; set; }
public string carrierServiceCode { get; set; }
public string exportVoyageNumber { get; set; }
public string importVoyageNumber { get; set; }
public int transportCallSequenceNumber { get; set; }
public string UNLocationCode { get; set; }
public string facilityCode { get; set; }
public string facilityCodeListProvider { get; set; }
public string facilityTypeCode { get; set; }
public string otherFacility { get; set; }
public string modeOfTransport { get; set; }
public Location location { get; set; }
public Vessel vessel { get; set; }
}
public partial class Location
{
public string LocationName { get; set; }
public string Latitude { get; set; }
public string Longitude { get; set; }
public string UnLocationCode { get; set; }
public string FacilityCode { get; set; }
public string FacilityCodeListProvider { get; set; }
}
public partial class Vessel
{
public long VesselImoNumber { get; set; }
public string VesselName { get; set; }
public string VesselFlag { get; set; }
public string VesselCallSignNumber { get; set; }
public string VesselOperatorCarrierCode { get; set; }
public string VesselOperatorCarrierCodeListProvider { get; set; }
}
static readonly string myJson = #"{
""events"": [
{
""eventID"": ""6832920321"",
""eventType"": ""SHIPMENT"",
""eventDateTime"": ""2019-11-12T07:41:00+08:00"",
""eventCreatedDateTime"": ""2021-01-09T14:12:56Z"",
""eventClassifierCode"": ""ACT"",
""shipmentEventTypeCode"": ""DRFT"",
""documentTypeCode"": ""SHI"",
""documentID"": ""205284917""
},
{
""eventID"": ""6832920321"",
""eventType"": ""TRANSPORT"",
""eventDateTime"": ""2019-11-12T07:41:00+08:00"",
""eventCreatedDateTime"": ""2021-01-09T14:12:56Z"",
""eventClassifierCode"": ""ACT"",
""transportEventTypeCode"": ""ARRI"",
""documentReferences"": [
{
""documentReferenceType"": ""BKG"",
""documentReferenceValue"": ""ABC123123123""
},
{
""documentReferenceType"": ""TRD"",
""documentReferenceValue"": ""85943567-eedb-98d3-f4ed-aed697474ed4""
}
],
""transportCall"": {
""transportCallID"": ""123e4567-e89b-12d3-a456-426614174000"",
""carrierServiceCode"": ""FE1"",
""exportVoyageNumber"": ""2103S"",
""importVoyageNumber"": ""2103N"",
""transportCallSequenceNumber"": 2,
""UNLocationCode"": ""USNYC"",
""facilityCode"": ""ADT"",
""facilityCodeListProvider"": ""SMDG"",
""facilityTypeCode"": ""POTE"",
""otherFacility"": ""Balboa Port Terminal, Avenida Balboa Panama"",
""modeOfTransport"": ""VESSEL"",
""location"": {
""locationName"": ""Eiffel Tower"",
""latitude"": ""48.8585500"",
""longitude"": ""2.294492036"",
""UNLocationCode"": ""USNYC"",
""facilityCode"": ""ADT"",
""facilityCodeListProvider"": ""SMDG""
},
""vessel"": {
""vesselIMONumber"": 1801323,
""vesselName"": ""King of the Seas"",
""vesselFlag"": ""DE"",
""vesselCallSignNumber"": ""NCVV"",
""vesselOperatorCarrierCode"": ""MAEU"",
""vesselOperatorCarrierCodeListProvider"": ""NMFTA""
}
}
}
]
}";
EDIT: Result is something like:

App is freezing when trying to deserialize Json string to object

I'm not sure what is causing this to happen. When debugging, I can step through each line, but when it hits the DeserializeObject line, the program doesn't do anything. I can no longer step over or do anything else with the program. No error messages are being thrown either.
[Command("stats")]
public async Task LookupMonsterStats(CommandContext ctx, string name)
{
string monstersUri = "https://www.dnd5eapi.co/api/monsters/";
var formatted = name.Replace(" ", "-");
string apiResponse = string.Empty;
using (var httpClient = new HttpClient())
{
using (var response = await httpClient.GetAsync(monstersUri + formatted))
{
apiResponse = await response.Content.ReadAsStringAsync();
var monster = JsonConvert.DeserializeObject<Monster>(apiResponse);
}
}
await ctx.Channel.SendMessageAsync(apiResponse).ConfigureAwait(false);
}
Edit: Here is what my Monster class looks like
public class Monster
{
[JsonProperty("index")]
public string Index { get; set; }
[JsonProperty("name")]
public string Name{ get; set; }
[JsonProperty("size")]
public string Size { get; set; }
[JsonProperty("type")]
public string Type { get; set; }
[JsonProperty("subtype")]
public string Subtype { get; set; }
[JsonProperty("alignment")]
public string Alignment { get; set; }
[JsonProperty("armor_class")]
public int? ArmorClass { get; set; }
[JsonProperty("hit_points")]
public int? HitPoints { get; set; }
[JsonProperty("forms")]
public List<string> Forms { get; set; }
[JsonProperty("speed")]
public Object Speed { get; set; }
[JsonProperty("strength")]
public int? Strength { get; set; }
[JsonProperty("dexterity")]
public int? Dexterity { get; set; }
[JsonProperty("constitution")]
public int? Constitution { get; set; }
[JsonProperty("intelligence")]
public int? Intelligence { get; set; }
[JsonProperty("wisdom")]
public int? Wisdom { get; set; }
[JsonProperty("charisma")]
public int? Charisma { get; set; }
[JsonProperty("proficiencies")]
public List<string> Proficiencies { get; set; }
[JsonProperty("damage_vulnerabilities")]
public List<string> DamageVulnerabilities { get; set; }
[JsonProperty("damage_resistances")]
public List<string> DamageResistances { get; set; }
[JsonProperty("damage_immunities")]
public List<string> DamageImmunities { get; set; }
[JsonProperty("condition_immunities")]
public List<string> ConditionImmunities { get; set; }
[JsonProperty("senses")]
public Object Senses { get; set; }
[JsonProperty("languages")]
public string Languages { get; set; }
[JsonProperty("challenge_rating")]
public decimal? ChallengeRating { get; set; }
[JsonProperty("special_abilities")]
public List<string> SpecialAbilities { get; set; }
[JsonProperty("actions")]
public List<string> Actions { get; set; }
[JsonProperty("legendary_actions")]
public List<string> LegendaryActions { get; set; }
[JsonProperty("url")]
public string Url { get; set; }
}
As mentioned in a comment your class definition doesn't seem to match the JSON response, assuming you're using Visual Studio it's probably worth opening Debug / Windows / Exception Settings and make sure "Common Language Runtime Exceptions" is checked. Sometimes I've found stepping over in multi-threaded apps can produce unusual results after an exception.
When I pasted your code into LINQPad I got errors on several members you've defined as List<string> when the underlying type is more complex. What I normally do to avoid those errors is copy the raw json from a browser window to the clipboard and with a CS file open in Visual Studio do an Edit / Paste Special / Paste JSON as classes to automatically create the classes. After doing that I got the following that deserialized the data fine:
async Task Main()
{
await LookupMonsterStats("aboleth");
}
public async Task LookupMonsterStats(string name)
{
string monstersUri = "https://www.dnd5eapi.co/api/monsters/";
var formatted = name.Replace(" ", "-");
string apiResponse = string.Empty;
using (var httpClient = new HttpClient())
{
using (var response = await httpClient.GetAsync(monstersUri + formatted))
{
apiResponse = await response.Content.ReadAsStringAsync();
var monster = JsonConvert.DeserializeObject<Monster>(apiResponse);
monster.Dump();
}
}
}
public class Monster
{
public string index { get; set; }
public string name { get; set; }
public string size { get; set; }
public string type { get; set; }
public object subtype { get; set; }
public string alignment { get; set; }
public int armor_class { get; set; }
public int hit_points { get; set; }
public string hit_dice { get; set; }
public Speed speed { get; set; }
public int strength { get; set; }
public int dexterity { get; set; }
public int constitution { get; set; }
public int intelligence { get; set; }
public int wisdom { get; set; }
public int charisma { get; set; }
public Proficiency[] proficiencies { get; set; }
public object[] damage_vulnerabilities { get; set; }
public object[] damage_resistances { get; set; }
public object[] damage_immunities { get; set; }
public object[] condition_immunities { get; set; }
public Senses senses { get; set; }
public string languages { get; set; }
public int challenge_rating { get; set; }
public int xp { get; set; }
public Special_Abilities[] special_abilities { get; set; }
public Action[] actions { get; set; }
public Legendary_Actions[] legendary_actions { get; set; }
public string url { get; set; }
}
public class Speed
{
public string walk { get; set; }
public string swim { get; set; }
}
public class Senses
{
public string darkvision { get; set; }
public int passive_perception { get; set; }
}
public class Proficiency
{
public Proficiency1 proficiency { get; set; }
public int value { get; set; }
}
public class Proficiency1
{
public string index { get; set; }
public string name { get; set; }
public string url { get; set; }
}
public class Special_Abilities
{
public string name { get; set; }
public string desc { get; set; }
public Dc dc { get; set; }
}
public class Dc
{
public Dc_Type dc_type { get; set; }
public int dc_value { get; set; }
public string success_type { get; set; }
}
public class Dc_Type
{
public string index { get; set; }
public string name { get; set; }
public string url { get; set; }
}
public class Action
{
public string name { get; set; }
public string desc { get; set; }
public Options options { get; set; }
public Damage[] damage { get; set; }
public int attack_bonus { get; set; }
public Dc1 dc { get; set; }
public Usage usage { get; set; }
}
public class Options
{
public int choose { get; set; }
public From[][] from { get; set; }
}
public class From
{
public string name { get; set; }
public int count { get; set; }
public string type { get; set; }
}
public class Dc1
{
public Dc_Type1 dc_type { get; set; }
public int dc_value { get; set; }
public string success_type { get; set; }
}
public class Dc_Type1
{
public string index { get; set; }
public string name { get; set; }
public string url { get; set; }
}
public class Usage
{
public string type { get; set; }
public int times { get; set; }
}
public class Damage
{
public Damage_Type damage_type { get; set; }
public string damage_dice { get; set; }
}
public class Damage_Type
{
public string index { get; set; }
public string name { get; set; }
public string url { get; set; }
}
public class Legendary_Actions
{
public string name { get; set; }
public string desc { get; set; }
public int attack_bonus { get; set; }
public Damage1[] damage { get; set; }
}
public class Damage1
{
public Damage_Type1 damage_type { get; set; }
public string damage_dice { get; set; }
}
public class Damage_Type1
{
public string index { get; set; }
public string name { get; set; }
public string url { get; set; }
}

Passing value to Class Object Created using json2csharp [duplicate]

This question already has answers here:
What is a NullReferenceException, and how do I fix it?
(27 answers)
Closed 6 years ago.
I have created class of below json using json2csharp.
{
"saveExistingRetailCustomerReq":{
"reqHdr":{
"consumerContext":{
"applicationId":"CRM",
"terminalId":"12345"
},
"serviceContext":{
"uniqueMsgId":"111121362162",
"reqMsgDateTime":"2016-09-02T11:19:15.754",
"timeZone":"2016-09-02T11:19:15.754",
"serviceName":"saveExistingRetailCustomer",
"serviceVersion":"1",
"conversationId":"2121211",
"parentMsgId":" 3132121"
},
"providerContext":{
"providerId":"CBS"
},
"userContext":{
"userId":" 132123"
},
"additionalDetails":{
"details":"1"
}
},
"body":{
"customerDtls":{
"custId":"22551",
"firstName":"First",
"lastName":"Last",
"middleName":"Middle",
"customerStatus":"DCSED",
"dateOfNotification":"2016-10-01T00:00:00.000",
"dateOfDeath":"2016-10-01T00:00:00.000",
"isSuspended":"Y",
"isNegated":"N",
"isBlacklisted":"N",
"gender":"",
"dateOfBirth":"1991-08-12T00:00:00.000",
"nativeLanguage":"Language",
"occupation":"",
"preferredName":"preferred",
"shortName":"short",
"primarySolId":"1100",
"title":"",
"SMSBankingMobNum":"9092480244",
"IsSMSBankingEnabled":"N",
"IsEBankingEnabled":"N",
"staffEmployeeID":"",
"staffFlag":"N",
"relatedDtls":{
"employmentStatus":"Salaried",
"maritalStatus":"002",
"nationality":"F"
},
"communicationDtls":{
"phoneDtls":{
"cityCode":"91",
"countryCode":"91",
"mobileNumber":"9092480244",
"phoneOrEmail":"PHONE",
"prefFlag":"Y",
"type":"HOMEPH1"
},
"emailDtls":{
"email":"test#email.com",
"type":"HOMEEML",
"phoneOrEmail":"EMAIL",
"prefFlag":"Y"
}
},
"addressDtls":[
{
"addressLine1":"AddressLine1",
"addressLine2":"AddressLine2",
"addressLine3":"AddressLine3",
"addressCategory":"Mailing",
"city":"C001",
"country":"IN",
"freeTextLabel":"RETAL",
"preferredAddress":"N",
"preferredFormat":"FREE_TEXT_FORMAT",
"startDt":"2005-07-02T00:00:00.000",
"state":"S001",
"postalCode":"507001"
},
{
"addressLine1":"Line1Address",
"addressLine2":"Line2Address",
"addressLine3":"Line3Address",
"addressCategory":"Swift",
"city":"C001",
"country":"IN",
"freeTextLabel":"RETAL",
"preferredAddress":"Y",
"preferredFormat":"FREE_TEXT_FORMAT",
"startDt":"2005-07-02T00:00:00.000",
"state":"S001",
"postalCode":"507001"
}
],
"documentDtls":[
{
"countryOfIssue":"IN",
"docCode":"IDPC",
"issueDt":"2015-09-12T00:00:00.000",
"type":"ID",
"placeOfIssue":"C001",
"referenceNum":"XYZ123VW45",
"preferredUniqueId":"Y",
"idIssuedOrganisation":"GOI"
},
{
"countryOfIssue":"IN",
"docCode":"IDVC",
"issueDt":"2015-08-12T00:00:00.000",
"type":"ID",
"placeOfIssue":"C001",
"referenceNum":"DEF123VW45",
"preferredUniqueId":"N",
"idIssuedOrganisation":"GOI"
}
]
}
}
}
}
Below is the Class created by json2Csharp.
using System.Collections.Generic;
namespace CRMnext.Ujjivan.DLL
{
public class ConsumerContext
{
public string applicationId { get; set; }
public string terminalId { get; set; }
}
public class ServiceContext
{
public string uniqueMsgId { get; set; }
public string reqMsgDateTime { get; set; }
public string timeZone { get; set; }
public string serviceName { get; set; }
public string serviceVersion { get; set; }
public string conversationId { get; set; }
public string parentMsgId { get; set; }
}
public class ProviderContext
{
public string providerId { get; set; }
}
public class UserContext
{
public string userId { get; set; }
}
public class AdditionalDetails
{
public string details { get; set; }
}
public class ReqHdr
{
public ConsumerContext consumerContext { get; set; }
public ServiceContext serviceContext { get; set; }
public ProviderContext providerContext { get; set; }
public UserContext userContext { get; set; }
public AdditionalDetails additionalDetails { get; set; }
}
public class RelatedDtls
{
public string employmentStatus { get; set; }
public string maritalStatus { get; set; }
public string nationality { get; set; }
}
public class PhoneDtls
{
public string cityCode { get; set; }
public string countryCode { get; set; }
public string mobileNumber { get; set; }
public string phoneOrEmail { get; set; }
public string prefFlag { get; set; }
public string type { get; set; }
}
public class EmailDtls
{
public string email { get; set; }
public string type { get; set; }
public string phoneOrEmail { get; set; }
public string prefFlag { get; set; }
}
public class CommunicationDtls
{
public PhoneDtls phoneDtls { get; set; }
public EmailDtls emailDtls { get; set; }
}
public class AddressDtl
{
public string addressLine1 { get; set; }
public string addressLine2 { get; set; }
public string addressLine3 { get; set; }
public string addressCategory { get; set; }
public string city { get; set; }
public string country { get; set; }
public string freeTextLabel { get; set; }
public string preferredAddress { get; set; }
public string preferredFormat { get; set; }
public string startDt { get; set; }
public string state { get; set; }
public string postalCode { get; set; }
}
public class DocumentDtl
{
public string countryOfIssue { get; set; }
public string docCode { get; set; }
public string issueDt { get; set; }
public string type { get; set; }
public string placeOfIssue { get; set; }
public string referenceNum { get; set; }
public string preferredUniqueId { get; set; }
public string idIssuedOrganisation { get; set; }
}
public class CustomerDtls
{
public string custId { get; set; }
public string firstName { get; set; }
public string lastName { get; set; }
public string middleName { get; set; }
public string customerStatus { get; set; }
public string dateOfNotification { get; set; }
public string dateOfDeath { get; set; }
public string isSuspended { get; set; }
public string isNegated { get; set; }
public string isBlacklisted { get; set; }
public string gender { get; set; }
public string dateOfBirth { get; set; }
public string nativeLanguage { get; set; }
public string occupation { get; set; }
public string preferredName { get; set; }
public string shortName { get; set; }
public string primarySolId { get; set; }
public string title { get; set; }
public string SMSBankingMobNum { get; set; }
public string IsSMSBankingEnabled { get; set; }
public string IsEBankingEnabled { get; set; }
public string staffEmployeeID { get; set; }
public string staffFlag { get; set; }
public RelatedDtls relatedDtls { get; set; }
public CommunicationDtls communicationDtls { get; set; }
public List<AddressDtl> addressDtls { get; set; }
public List<DocumentDtl> documentDtls { get; set; }
}
public class Body
{
public CustomerDtls customerDtls { get; set; }
}
public class SaveExistingRetailCustomerReq
{
public ReqHdr reqHdr { get; set; }
public Body body { get; set; }
}
public class RootObject
{
public SaveExistingRetailCustomerReq saveExistingRetailCustomerReq { get; set; }
}
}
In the next step I want to pass values in this created class. After that by serializing object of this class I want to pass that serialized Json to one service I am consuming. I have tried below by referring Turn C# object into a JSON string in .NET 4. But getting error Object reference not set to an instance of an object.
RootObject rootObject = new RootObject();
rootObject.saveExistingRetailCustomerReq.reqHdr.consumerContext.applicationId = "CRM";
var jsonData = JsonConvert.SerializeObject(rootObject);
If I am doing anything wrong then I would appreciate if anyone could guide me in this process.
You need create all objects not only RootObject.
RootObject rootObject = new RootObject();
rootObject.saveExistingRetailCustomerReq = new SaveExistingRetailCustomerReq();
rootObject.saveExistingRetailCustomerReq.reqHdr = new ReqHdr();
rootObject.saveExistingRetailCustomerReq.reqHdr.consumerContext = new ConsumerContext();
rootObject.saveExistingRetailCustomerReq.reqHdr.consumerContext.applicationId = "CRM";
var jsonData = JsonConvert.SerializeObject(rootObject);

Windows 8 store , Json Deserialize

im trying to deserialize a Json that i get from a webservice Like so:
Uri urlJson = new Uri("http://optimizingconcepts.com/staging/cartuxa/system/json_request.php?lang=pt");
var client = new HttpClient();
HttpResponseMessage response = await client.GetAsync(urlJson);
var jsonString = await response.Content.ReadAsStringAsync();
the Json i get is this:http://paste2.org/MpYJd8kk
I then do this to get the JsonObject:
JsonObject root = Windows.Data.Json.JsonValue.Parse(jsonString).GetObject();
What i want to know, is the correct way of saving each object from json to a list
so the objects from "home" would be in a List, the objects from "artigos" would go to a List and so on.
Using Json.Net, it can be done as follows
Uri urlJson = new Uri("http://optimizingconcepts.com/staging/cartuxa/system/json_request.php?lang=pt");
var client = new HttpClient();
var json = await client.GetStringAsync(urlJson);
var obj = JsonConvert.DeserializeObject<Cartuxa.RootObject>(json);
I used http://json2csharp.com/ to generate below classes.
public class Cartuxa
{
public class Home
{
public object id { get; set; }
public string menu { get; set; }
public string title { get; set; }
public string image { get; set; }
public string url { get; set; }
}
public class Artigo
{
public string menu { get; set; }
public string submenu { get; set; }
public string title { get; set; }
public string subtitle { get; set; }
public string description { get; set; }
public List<object> media { get; set; }
}
public class Year
{
public string year { get; set; }
public string title { get; set; }
public string description { get; set; }
public string file { get; set; }
public string url { get; set; }
}
public class Product
{
public string id { get; set; }
public string image { get; set; }
public string url { get; set; }
public List<Year> year { get; set; }
}
public class Vinho
{
public string id { get; set; }
public string menu { get; set; }
public string submenu { get; set; }
public string title { get; set; }
public List<Product> product { get; set; }
}
public class Year2
{
public string year { get; set; }
public string title { get; set; }
public string description { get; set; }
public string file { get; set; }
public string url { get; set; }
}
public class Product2
{
public string id { get; set; }
public string image { get; set; }
public string url { get; set; }
public List<Year2> year { get; set; }
}
public class Azeite
{
public string id { get; set; }
public string menu { get; set; }
public string submenu { get; set; }
public string title { get; set; }
public List<Product2> product { get; set; }
}
public class Agente
{
public string id { get; set; }
public string continent_id { get; set; }
public string country_id { get; set; }
public string title { get; set; }
public string description { get; set; }
}
public class Continente
{
public string id { get; set; }
public string title { get; set; }
}
public class Pais
{
public string id { get; set; }
public string continent_id { get; set; }
public string title { get; set; }
}
public class Contacto
{
public string id { get; set; }
public string menu_id { get; set; }
public string submenu_id { get; set; }
public string title { get; set; }
public string address { get; set; }
public string phone { get; set; }
public string fax { get; set; }
public string longitude { get; set; }
public string latitude { get; set; }
}
public class Premio
{
public string image { get; set; }
public string url { get; set; }
}
public class Noticia
{
public string id { get; set; }
public string menu { get; set; }
public string date_created { get; set; }
public string title { get; set; }
public string subtitle { get; set; }
public string description { get; set; }
public List<object> media { get; set; }
}
public class RootObject
{
public List<Home> home { get; set; }
public List<Artigo> artigos { get; set; }
public List<Vinho> vinhos { get; set; }
public List<Azeite> azeites { get; set; }
public List<Agente> agentes { get; set; }
public List<Continente> continentes { get; set; }
public List<Pais> paises { get; set; }
public List<Contacto> contactos { get; set; }
public List<Premio> premios { get; set; }
public List<Noticia> noticias { get; set; }
}
}

Categories