MVC model returns null - json

I have a json string in my controller. When i deserialize that into my model, it's returning a null value. The very strange part here is that this was working a while ago then stopped. Any thoughts as to what's wrong here? This is an api call, so i don't have the luxury of changing the json either. tCustLst is the problem child that is returning null from the model.
json (result):
"{\"response\":{\"cErrorMessage\":\"\",\"moreRecordsAvailable\":false,\"tCustLst\":{\"t-custLst\":[{\"custNo\":324161.0,\"shipTo\":\"\",\"name\":\"TEST \\/ (NICKNAME)\",\"addr1\":\"P.O. BOX 111\",\"addr2\":\"\",\"city\":\"NYC\",\"state\":\"NY\",\"zipCd\":\"55555-1234\",\"ordBal\":0.0,\"totalBal\":20451.67,\"sortFld\":\" 123456\"}]}}}"
controller code:
CustomerList.Rootobject records = JsonConvert.DeserializeObject<CustomerList.Rootobject>(result);
return View(records);
model:
using Newtonsoft.Json;
using System.Collections.Generic;
namespace WebappsIntranet.Models
{
public class CustomerList
{
public class Rootobject
{
public string cErrorMessage { get; set; }
public bool moreRecordsAvailable { get; set; }
public tCustLst tCustList { get; set; }
}
public class tCustLst
{
[JsonProperty("t-custLst")]
public List<tCustcomerList> tcustomerlist { get; set; }
}
public class tCustcomerList {
public float custNo { get; set; }
public string shipTo { get; set; }
public string name { get; set; }
public string addr1 { get; set; }
public string addr2 { get; set; }
public string city { get; set; }
public string state { get; set; }
public string zipCd { get; set; }
public float ordBal { get; set; }
public float totalBal { get; set; }
public string sortFld { get; set; }
}
}
}

Related

Post Request gives a 405 error in Postman

on my .Net Web Api, I have an entity model, request model and response model for each database table. When i make a post request to MedTestOrder, i receive a 405 error, but other entities are working fine. I will post code snippets of MedTestOrder entity model, request model, response model, controller and service. The models contain foreign keys and I suspect my error could be from there. I might be wrong or not. I just need help.
1 - Entity Model
namespace Africanbiomedtests.Entities
{
public class MedTestOrder
{
[Key]
public int Id { get; set; }
public int? MedTestId { get; set; }
[ForeignKey("MedTestId")]
public MedTest MedTest { get; set; }
public int? healthcareProviderId { get; set; }
[ForeignKey("healthcareProviderId")]
public HealthcareProvider healthcareProvider { get; set; }
public int? accountId { get; set; }
[ForeignKey("accountId")]
public Account Account { get; set; }
public int? newbornId { get; set; }
[ForeignKey("newbornId")]
public Newborn Newborn { get; set; }
public string PaymentStatus { get; set; }
public Boolean CompletionStatus { get; set; }
public DateTime DateCreated { get; set; }
public DateTime DateCompleted { get; set; }
public DateTime? Updated { get; set; }
}
}
2 - Api Request Model
namespace Africanbiomedtests.Models.MedTestsOrder
{
public class MedTestsOrderCreateRequest
{
[Required]
public MedTest MedTest { get; set; }
public HealthcareProvider healthcareProvider { get; set; }
public Account Account { get; set; }
public Newborn Newborn { get; set; }
[Required]
public string PaymentStatus { get; set; }
public Boolean CompletionStatus { get; set; }
[Required]
public DateTime DateCreated { get; set; }
}
}
3 - Response Model
namespace Africanbiomedtests.Models.MedTestsOrder
{
public class MedTestsOrderResponse
{
public int Id { get; set; }
public MedTest MedTest { get; set; }
public HealthcareProvider healthcareProvider { get; set; }
public Account Account { get; set; }
public Newborn Newborn { get; set; }
public string PaymentStatus { get; set; }
public Boolean CompletionStatus { get; set; }
public DateTime DateCreated { get; set; }
public DateTime DateCompleted { get; set; }
}
}
4 - Controller
[Authorize]
[HttpPost("create")]
public ActionResult<MedTestsOrderResponse> Create(MedTestsOrderCreateRequest model)
{
var medTestOrder = _medTestOrderService.Create(model);
return Ok(medTestOrder);
}
5 - Service
public MedTestsOrderResponse Create(MedTestsOrderCreateRequest model)
{
// map model to new account object
var medTestOrder = _mapper.Map<MedTestOrder>(model);
medTestOrder.DateCreated = DateTime.UtcNow;
// save account
_context.MedTestOrder.Add(medTestOrder);
_context.SaveChanges();
return _mapper.Map<MedTestsOrderResponse>(medTestOrder);
}
6 - Postman JSON request
{
"medTestId": 3,
"healthcareProviderId": 3,
"accountId": 1004,
"newbornId": 1,
"paymentStatus": "Complete Payment",
"completionStatus": "1",
"dateCompleted": "01/14/2021"
}
I would really appreciate any help right now
Thank you #Marius and #Karney, I realized i wasn't using the correct endpoint. I needed to add "/create" to my endpoint.
In some cases, your Web API method accepts only PUT requests, Try to put not post.

Object is always empty when deserialize on xamarin service

Have this service built on a xamarin app:
public class OpenWeatherMap<T>
{
private const string OpenWeatherApi = "http://api.openweathermap.org/data/2.5/weather?q=";
private const string Key = "653b1f0bf8a08686ac505ef6f05b94c2";
HttpClient _httpClient = new HttpClient();
// aqui podemos enviar directo a una ciudad hardcoded
public async Task<T> GetAllWeathers(string city)
{
var json = await _httpClient.GetStringAsync(OpenWeatherApi + city + "&APPID=" + Key);
var getWeatherModels = JsonConvert.DeserializeObject<T>(json);
return getWeatherModels;
}
}
When i check the model object is always empty. JSON is fine and my class matches perfectly my JSON model. I'm using Newtonsoft.Json.
This is my model:
public class WeatherMainModel
{
[JsonProperty("coord")]
public Coord Coord { get; set; }
[JsonProperty("weather")]
public WeatherSubDetails[] Weather { get; set; }
[JsonProperty("base")]
public string Base { get; set; }
[JsonProperty("main")]
public Main Main { get; set; }
[JsonProperty("visibility")]
public string Visibility { get; set; }
[JsonProperty("wind")]
public WeatherWindDetails Wind { get; set; }
[JsonProperty("clouds")]
public Clouds Clouds { get; set; }
[JsonProperty("dt")]
public string Dt { get; set; }
[JsonProperty("sys")]
public WeatherSysDetails Sys { get; set; }
[JsonProperty("id")]
public string Id { get; set; }
[JsonProperty("name")]
public string Name { get; set; }
[JsonProperty("cod")]
public string Cod { get; set; }
}
public partial class Clouds // new
{
[JsonProperty("all")]
public string All { get; set; }
}
public partial class Coord // new
{
[JsonProperty("lon")]
public string Lon { get; set; }
[JsonProperty("lat")]
public string Lat { get; set; }
}
public partial class Main
{
[JsonProperty("temp")]
public string Temp { get; set; }
[JsonProperty("pressure")]
public string Pressure { get; set; }
[JsonProperty("humidity")]
public string Humidity { get; set; }
[JsonProperty("temp_min")]
public string TempMin { get; set; }
[JsonProperty("temp_max")]
public string TempMax { get; set; }
}
public partial class WeatherSysDetails
{
[JsonProperty("type")]
public string Type { get; set; }
[JsonProperty("id")]
public string Id { get; set; }
[JsonProperty("message")]
public string Message { get; set; }
[JsonProperty("country")]
public string Country { get; set; }
[JsonProperty("sunrise")]
public string Sunrise { get; set; }
[JsonProperty("sunset")]
public string Sunset { get; set; }
}
public partial class WeatherSubDetails
{
[JsonProperty("id")]
public string Id { get; set; }
[JsonProperty("main")]
public string Main { get; set; }
[JsonProperty("description")]
public string Description { get; set; }
[JsonProperty("icon")]
public string Icon { get; set; }
}
public partial class WeatherWindDetails
{
[JsonProperty("speed")]
public string Speed { get; set; }
[JsonProperty("deg")]
public string Deg { get; set; }
}
I'm using visual studio community set for Latin America (Chile), so i tried changing every decimal field on the JSON to string on the model to avoid comma separation problems, but still, my object is coming empty no matter the JSON i inject to the deserializer.
Thanks in advance.

How to parse json with object and List for the same attribute? C#

On trying to parse JSON, I got an error about types. I have this code:
public class Event
{
[JsonProperty("eventKey")]
public int EventKey { get; set; }
[JsonProperty("displayOrder")]
public int DisplayOrder { get; set; }
[JsonProperty("subTypeKey")]
public int SubTypeKey { get; set; }
[JsonProperty("eventName")]
public string EventName { get; set; }
[JsonProperty("eventNameTranslated")]
public string EventNameTranslated { get; set; }
[JsonProperty("eventStatus")]
public string EventStatus { get; set; }
[JsonProperty("eventSort")]
public string EventSort { get; set; }
[JsonProperty("eventDateTime")]
public DateTime EventDateTime { get; set; }
[JsonProperty("classSortCode")]
public string ClassSortCode { get; set; }
[JsonProperty("typeFlagCode")]
public string TypeFlagCode { get; set; }
}
public class Events
{
[JsonProperty("num")]
public int Num { get; set; }
[JsonProperty("event")]
public IList<Event> Event { get; set; }
}
public class Subtype
{
[JsonProperty("subTypeKey")]
public int SubTypeKey { get; set; }
[JsonProperty("subTypeName")]
public string SubTypeName { get; set; }
[JsonProperty("displayOrder")]
public int DisplayOrder { get; set; }
[JsonProperty("events")]
public Events Events { get; set; }
}
public class Subtypes
{
[JsonProperty("num")]
public int Num { get; set; }
[JsonProperty("subtype")]
public Subtype Subtype { get; set; }
}
But I am getting error, because it can't parse it, cause sometimes it have type as List, sometimes as object. See screenshot (subtype and event).
How can I change my code to support different types?
Can you help me with this? Or what I need to read, to solve my problem?

Xamarin Json parsing

Ι am having a json like this:
{"userTweetsList":[{"tweetId":1,"tweetData":"testing uploading from uwp","createdTime":1510822592529,"commentCount":0,"likeCount":1,"flagCount":1,"mediaUrl":"suburl","tweetUser":"geo.thomas","userLiked":true,"userFlagged":true},{"tweetId":2,"tweetData":"Testing tweet","createdTime":1510821224655,"commentCount":0,"likeCount":0,"flagCount":1,"mediaUrl":"suburl","tweetUser":"sreejith.sree","userLiked":false,"userFlagged":true}],"tweetUsersMapList":[{"geo.thomas":{"username":"geo.thomas","name":"geo thomas ","profileImage":null}},{"sreejith.sree":{"username":"sreejith.sree","name":"sreejith sreenivasan","profileImage":null}}],"urlFileserverDynamic":"MyBaseUrl"}
My model class:
public class UserTweetResponse
{
public List<UserTweetsList> userTweetsList { get; set; }
}
public class UserTweetsList
{
public int tweetId { get; set; }
public string tweetData { get; set; }
public string createdTime { get; set; }
public int commentCount { get; set; }
public int likeCount { get; set; }
public int flagCount { get; set; }
public string mediaUrl { get; set; }
public string tweetUser { get; set; }
public bool userLiked { get; set; }
public bool userFlagged { get; set; }
public bool isMediaUrlNull { get { return string.IsNullOrEmpty(mediaUrl); } }
}
In my cs file, I link the listview with the userTweetsList, My listview name is ListView1.
ListView1.ItemsSource = userTweetResponse.userTweetsList;
I can access the all the data in the userTweetsList using {binding} property.
My problem is I need to access and show the name in ui based on the tweet user value. Suppose the "tweetUser":"geo.thomas" i need to access the
{"geo.thomas":{"username":"geo.thomas","name":"geo thomas ","profileImage":null}} inside the tweetUsersMapList, same way for "tweetUser":"sreejith.sree"
i need the data
{"sreejith.sree":{"username":"sreejith.sree","name":"sreejith sreenivasan","profileImage":null}}
For this I change the model like this:
public class UserTweetResponse
{
public List<UserTweetsList> userTweetsList { get; set; }
public List<TweetUsersMapList> tweetUsersMapList { get; set; }
}
public class UserTweetsList
{
public int tweetId { get; set; }
public string tweetData { get; set; }
public string createdTime { get; set; }
public int commentCount { get; set; }
public int likeCount { get; set; }
public int flagCount { get; set; }
public string mediaUrl { get; set; }
public string tweetUser { get; set; }
public bool userLiked { get; set; }
public bool userFlagged { get; set; }
public bool isMediaUrlNull { get { return string.IsNullOrEmpty(mediaUrl); } }
}
public class TweetUsersMapList
{
public string username { get; set; }
public string name { get; set; }
public string profileImage { get; set; }
}
But i don't know how to do the rest part. How can i link the listview with tweetUsersMapList? Based on the tweetUser name how can i pick the name and show that in the ui?
Is it possible to parse this type of complex json?
Anybody, please suggest a solution
Thanks in advance...
public class UserTweetsList
{
public int tweetId { get; set; }
public string tweetData { get; set; }
public object createdTime { get; set; }
public int commentCount { get; set; }
public int likeCount { get; set; }
public int flagCount { get; set; }
public string mediaUrl { get; set; }
public string tweetUser { get; set; }
public bool userLiked { get; set; }
public bool userFlagged { get; set; }
}
public class GeoThomas
{
public string username { get; set; }
public string name { get; set; }
public object profileImage { get; set; }
}
public class SreejithSree
{
public string username { get; set; }
public string name { get; set; }
public object profileImage { get; set; }
}
public class TweetUsersMapList
{
public GeoThomas __invalid_name__geo.thomas { get; set; }
public SreejithSree __invalid_name__sreejith.sree { get; set; }
}
public class RootObject
{
public List<UserTweetsList> userTweetsList { get; set; }
public List<TweetUsersMapList> tweetUsersMapList { get; set; }
public string urlFileserverDynamic { get; set; }
}
I have used Json2csharp to generate these classes...

I am a new bee with JSON and I don't know how to perform serialization and deserialization in windows phone

get links will be like this - http//192.156.120.192/Projects/cricket/index.php/api/api
public class Player
{
public int playerId { get; set; }
public string playerName { get; set; }
public string specialization { get; set; }
public string battingHand { get; set; }
public string bowlingHand { get; set; }
public string bowlingType { get; set; }
public object genericId { get; set; }
public int homeTeamId { get; set; }
public int eligibleTeams { get; set; }
public object imageUrl { get; set; }
}
public class RootObject
{
public string methodName { get; set; }
public int errorCode { get; set; }
public string errorMessage { get; set; }
public List<Player> players { get; set; }
}
I am using Json.NET and it is super easy
// create a RootObject object
//..
string serializedRoot = JsonConvert.SerializeObject(myRootObject);
RootObject deserializedRoot = JsonConvert.DeserializeObject<Player>(serializedRoot);