How to send list of object to webapi c#? - c#

I'm trying to send a list of objects to webapi in json-array format. But, in the parameter its getting null.
Now, let me post the code that i have tried so far
[HttpPost]
[Route("~/api/visitsave")]
public IHttpActionResult Save(List<VisitDataModel> visitobj)
{
foreach (VisitDataModel visitobjs in visitobj) {
VisitManager obj = new VisitManager(visitobjs);
bool value = obj.Save();
}
return Ok();
}
This is the json-array I'm trying to pass, but it is not working in the parameter visitobj.
Its receiving null. As I'm new to webapi and c#, I'm struggling with this.
But when i pass single json object I'm getting values and when i switched back to list, it's not working.
Let me post the json array that am trying to post:
{"visitobj":[{"Remarks":"test","UserID":193,"FindingsAtSite":"nothing","CheckInDate":"2017-02-01 12:00:00","CheckOutDate":"2017-02-01 12:00:00","VisitStatusID":1,"CreatedBy":192,"CreatedDateTime":"2017-02-01 12:00:00","Claim":{"TransportMode":1,"Date":"2017-02-01 12:00:00","FromLocation":"chennai","ToLocation":"re","Ticket":123.2,"Conveyance":123.5,"Lodge":234.0,"Meals":23}}]}
This is the jsonresponse am trying to send to my webapi can someone helpme out this may be dumb question but am struggling with this. Thanks in advance!!

May be you are passing json in wrong format. I have an API action like this
[HttpPost]
[Route("sample")]
public IHttpActionResult SampleOp(List<SampleObj> smpJson)
{
foreach (var item in smpJson){
//Do Some Thing Here
}
return ok();
}
And passing the json data as
[{
"name":"name 1",
"address":"address 1",
"age":1
},
{
"name":"name 2",
"address":"address 2",
"age":2
}]
Here is my SampleObj modal
public class SampleObj {
public string name { get; set; }
public string address { get; set; }
public int age { get; set; }
}
It is tested and working here

This is a normal behavior since your contract does not match.
Change your parameters to the following and your argument will be ok
public class Claim
{
public int TransportMode { get; set; }
public string Date { get; set; }
public string FromLocation { get; set; }
public string ToLocation { get; set; }
public double Ticket { get; set; }
public double Conveyance { get; set; }
public double Lodge { get; set; }
public int Meals { get; set; }
}
public class Visitobj
{
public string Remarks { get; set; }
public int UserID { get; set; }
public string FindingsAtSite { get; set; }
public string CheckInDate { get; set; }
public string CheckOutDate { get; set; }
public int VisitStatusID { get; set; }
public int CreatedBy { get; set; }
public string CreatedDateTime { get; set; }
public Claim Claim { get; set; }
}
public class VisiteRequest
{
public List<Visitobj> visitobj { get; set; }
}
Or the second option you have to change the Json sent object as an array
[{"Remarks":"test","UserID":193,"FindingsAtSite":"nothing","CheckInDate":"2017-02-01 12:00:00","CheckOutDate":"2017-02-01 12:00:00","VisitStatusID":1,"CreatedBy":192,"CreatedDateTime":"2017-02-01 12:00:00","Claim":{"TransportMode":1,"Date":"2017-02-01 12:00:00","FromLocation":"chennai","ToLocation":"re","Ticket":123.2,"Conveyance":123.5,"Lodge":234.0,"Meals":23}}]

Related

ASP.NET Core post data not serealize custom field

I am using ASP.NET Core 3.1 and angular.
I send a post request from the object model to the controller method.
The controller method accepts an object at the input, but the bindingParameters field is empty.
The bindingParameters field is a list of KeyValueItem objects.
TmObject.cs
namespace v1.Atm
{
public class TmObject
{
[JsonProperty("id")]
public int Id { get; set; }
[JsonProperty("binding")]
public string Binding { get; set; }
[JsonProperty("sourceBindingParameters")]
public string SourceBindingParameters { get; set; }
[NotMapped]
[JsonProperty("bindingParameters")]
public List<TmKeyValueItem> BindingParameters
{
get
{
return JsonConvert.DeserializeObject<List<TmKeyValueItem>>(string.IsNullOrEmpty(SourceBindingParameters) ? "" : SourceBindingParameters);
}
set
{
SourceBindingParameters = JsonConvert.SerializeObject(value);
}
}
[JsonProperty("caption")]
public string Caption { get; set; }
[JsonProperty("description")]
public string Description { get; set; }
[JsonProperty("name")]
public string Name { get; set; }
[JsonIgnore]
public string SourceParameterGroups { get; set; }
[NotMapped]
[JsonProperty("parameterGroups")]
public List<string> ParameterGroups
{
get
{
return JsonConvert.DeserializeObject<List<string>>(string.IsNullOrEmpty(SourceParameterGroups) ? "" : SourceParameterGroups);
}
set
{
SourceParameterGroups = JsonConvert.SerializeObject(value);
}
}
[NotMapped]
[JsonProperty("parameters")]
public List<TmObjectParameter> Parameters;
[NotMapped]
[JsonProperty("removeParameters")]
public List<int> RemoveParameters { get; set; }
public TmObject()
{
Parameters = new List<TmObjectParameter>();
RemoveParameters = new List<int>();
}
}
}
If the bindingParameters field is changed, it works:
[NotMapped]
[JsonProperty("bindingParameters")]
public List<BindingParameter> BindingParameters{ get; set; }
Tell me, please, what could be the problem?
P.S. Prior to this, the project was implemented on ASP.NET Webforms and there the code described above worked.
update
I got out of the problem as follows. Opened the SourceBindingParameters field for visibility on the client by adding [JsonProperty ("sourceBindingParameters")]. And before sending data to the server, I serialize the values from BindingParameters to sourceBindingParameters.
public updateTmObject(tmObject: TmObject) {
tmObject.sourceBindingParameters = JSON.stringify(tmObject.bindingParameters);
return this.httpService.post('/v1/Editor/UpdateObject', JSON.stringify(tmObject.bindingParameters), this.httpOptions).subscribe(
(response: any) => {
this.reset();
this.getTmObjects();
return true;
},
error => {
console.error("TmObjects|TmObjectsService.updateTmObject(): " + error.status);
}
);
}
The bindingParameters from request is not a list of string values but complex objects. You'd better create a class for this objects
public class BindingParameter
{
public int Id { get; set; }
public string Key { get; set; }
public string Value { get; set; }
public bool Visible { get; set; }
}
and declare the property as the following
public List<BindingParameter> BindingParameters{ get; set; }

C# Parsing JSON String

I have tried countless methods to Parse my JSON string (Steam Public Data), yet nothing seems to work. I just want to be able to extract values from the string. For Example, obtaining the value of personaname which would return SlothGod. I have JSON.NET installed in my project.
Here is my JSON:
{
"response": {
"players": [
{
"steamid": "76561198301407459",
"communityvisibilitystate": 3,
"profilestate": 1,
"personaname": "SlothGod",
"lastlogoff": 1508389707,
"commentpermission": 1,
"profileurl": "http://steamcommunity.com/id/sleuthgud/",
"avatar": "https://steamcdn-a.akamaihd.net/steamcommunity/public/images/avatars/09/09cea52b91136fb3306c57771a746db2823b91ba.jpg",
"avatarmedium": "https://steamcdn-a.akamaihd.net/steamcommunity/public/images/avatars/09/09cea52b91136fb3306c57771a746db2823b91ba_medium.jpg",
"avatarfull": "https://steamcdn-a.akamaihd.net/steamcommunity/public/images/avatars/09/09cea52b91136fb3306c57771a746db2823b91ba_full.jpg",
"personastate": 0,
"realname": "Josh",
"primaryclanid": "103582791460168790",
"timecreated": 1462086929,
"personastateflags": 0,
"loccountrycode": "AU",
"locstatecode": "QLD"
}
]
}
}
Main method suggested to me:
public class Details
{
public string personaname { get; set; }
}
private void GetSteamDetails()
{
var data = Newtonsoft.Json.JsonConvert.DeserializeObject<Details>(SteamDetailsJson);
SteamName = data.personaname;
}
This is placed before Page_Load(). I then call GetSteamDetails(); when I want to fetch the name.
After my question being down voted, I decided to not give up on this problem. After extensive research, trial and error, and YouTube tutorials which are the most helpful IMO. I found that the data was containing a JSON array, and yes I will admit, I was confused with this, but the answer was to simply treat it like a C# array and add [1] to the end of players.
Details details = new Details();
public class Details
{
public string avatar { get; set; }
public string avatarmedium { get; set; }
public string avatarfull { get; set; }
public string realname { get; set; }
public string personaname { get; set; }
public string steamid { get; set; }
}
private void GetSteamDetails()
{
var SteamDetails= JsonConvert.DeserializeObject<dynamic>(SteamDetailsJson);
avatar = SteamDetails.response.players[1].avatar.ToString();
personaname = SteamDetails.response.players[1].personaname.ToString();
}
Based on the JSON string you provided, you should have the following C# classes to support it, or to deserialize the JSON object values into: I used this link to generate the classes.
public class Player
{
public string steamid { get; set; }
public int communityvisibilitystate { get; set; }
public int profilestate { get; set; }
public string personaname { get; set; }
public int lastlogoff { get; set; }
public int commentpermission { get; set; }
public string profileurl { get; set; }
public string avatar { get; set; }
public string avatarmedium { get; set; }
public string avatarfull { get; set; }
public int personastate { get; set; }
public string realname { get; set; }
public string primaryclanid { get; set; }
public int timecreated { get; set; }
public int personastateflags { get; set; }
public string loccountrycode { get; set; }
public string locstatecode { get; set; }
}
public class Response
{
public List<Player> players { get; set; }
}
public class RootObject
{
public Response response { get; set; }
}
Then, using Newtonsoft.Json, you can deserialize the JSON object into your C# classes as follow:
JsonConvert.DeserializeObject<RootObject>("yourJsonString");
You mention that Newtonsoft.Json already referenced in the project.
Use class to represent json data structure, then you can easy deserialize it.
You can use only properties you need in the class.
public class Player
{
public string personaname { get; set; }
}
var player = Newtonsoft.Json.JsonConvert.DeserializeObject<Player>(jsonString);
// use player.personaname
For updates question create classes which represent your data structure
public class Team
{
public List<Player> players { get; set; }
}
public class Response
{
public Team response { get; set; }
}
You can use http://json2csharp.com/ to generate a class automatically from a JSON string.

Unable to deserialize JSON in c#

I am getting the below JSON in response from a REST API.
{
"data":{
"id":123,
"zoneid":"mydomain.com",
"parent_id":null,
"name":"jaz",
"content":"172.1 6.15.235",
"ttl":60,
"priority":null,
"type":"A",
"regions":[
"global"
],
"system_record":false,
"created_at":"2017-09-28T12:12:17Z",
"updated_at":"2017-09-28T12:12:17Z"
}
}
and trying to resolve using below code but that doesn't result in a correctly deserialized type.
var model = JsonConvert.DeserializeObject<ResponseModel>(response);
below is a class according the field I received in JSON response.
public class ResponseModel
{
public int id { get; set; }
public string zone_id { get; set; }
public int parent_id { get; set; }
public string name { get; set; }
public string content { get; set; }
public int ttl { get; set; }
public int priority { get; set; }
public string type { get; set; }
public string[] regions { get; set; }
public bool system_record { get; set; }
public DateTime created_at { get; set; }
public DateTime updated_at { get; set; }
}
What is missing?
You're missing a wrapper class.
public class Wrapper
{
public ResponseModel data {get;set}
}
and then do:
var model = JsonConvert.DeserializeObject<Wrapper>(response).data;
to get the instance of your ResponseModel out the data property.
You can deduct this from your json:
{ "data":
{ "id":123, /*rest omitted */ }
}
The type that will receive this JSON needs to have a property named data. The suggested Wrapper class acts as that type.
According to json2csharp website, your model seems to be incorrect. Try this one :
public class ResponseModel
{
public int id { get; set; }
public string zoneid { get; set; }
public object parent_id { get; set; }
public string name { get; set; }
public string content { get; set; }
public int ttl { get; set; }
public object priority { get; set; }
public string type { get; set; }
public List<string> regions { get; set; }
public bool system_record { get; set; }
public DateTime created_at { get; set; }
public DateTime updated_at { get; set; }
}
public class RootObject
{
public ResponseModel data { get; set; }
}
Here a cool trick you can do in Visual Studio 2015-2017 where it generates the the correct class if you just copy the JSON (ctrl + c).
You need to create a new class in visual studio and once inside the class go to Edit menu -> Paste special -> paste JSON As Classes.
Steps to generate json class
This will generate the C# object for that json for you and save you all the hassle :)
Your model does not match your response - it matches the data property. Simply wrap another object round it
public class ResponseData
{
public ResponseModel Data {get; set; {
}
and then
var model = JsonConvert.DeserializeObject<ResponseData>(response);

Receiving JSON data on Web API Visual Studio C#

I have a web api which is receiving some POST data.
I am able to parse the JSON string when the elements are not nested - but the nested ones just will not parse at all...
Here is the JSON I am receiving:
{
"wlauth": {
"userid": "user",
"password": "pass"
},
"ident": "01234567890",
"identtype": "imsi",
"message": "VGVzdCBNZXNzYWdl"
}
Here is the code from the Controller that handles the Post request:
public IHttpActionResult ReceiveSMSData(SMSReturned data)
{
Debug.WriteLine(data.userid);
Debug.WriteLine(data.password);
Debug.WriteLine(data.Ident);
Debug.WriteLine(data.identtype);
Debug.WriteLine(data.message);
return Ok();
}
From this I get the following in the debug console (the first two lines are blank):
'
01234567890
imsi
VGVzdCBNZXNzYWdl'
So in other words, the non-nested elements appear fine, but the nested ones do not - what should I be doing differently to retrieve those nested elements?
Edit:
Here is the SMSReturned Class:
public class SMSReturned
{
public string wlauth { get; set; }
public string Ident { get; set; }
public string identtype { get; set; }
public string message { get; set; }
public string userid { get; set; }
public string password { get; set; }
}
The structure for SMSReturned is missing some elements. Try this:
public class WLAuth
{
public string userid { get; set; }
public string password { get; set; }
}
public class SMSReturned
{
public WLAuth wlauth { get; set; }
public string Ident { get; set; }
public string identtype { get; set; }
public string message { get; set; }
public string userid { get; set; }
public string password { get; set; }
}
and this:
public IHttpActionResult ReceiveSMSData(SMSReturned data)
{
Debug.WriteLine(data.wlauth.userid);
Debug.WriteLine(data.wlauth.password);
Debug.WriteLine(data.Ident);
Debug.WriteLine(data.identtype);
Debug.WriteLine(data.message);
return Ok();
}

JsonConvert.DeserializeObject from PubNub message

When I send in this message to MakeAction manually it works and the message box pops up:
string json = #"{'action':'turncompleted', 'messageID':'123123123', 'playerID':'100000067174580', 'round':1, 'values':[{'longitude':21.09375, 'latitude':24.527134822598}, {'longitude':1.40625, 'latitude':23.885837699862}]}";
public void MakeAction(string message)
{
Poker_Server_v4_0.Action a = JsonConvert.DeserializeObject<Poker_Server_v4_0.Action>(message);
System.Windows.Forms.MessageBox.Show(a.action + a.messageID);
}
But when I use the message from PubNub it doesn't work:
static void DisplaySubscribeReturnMessage(string result)
{
//Receives the message from Pubnub takes care of the Action.
MessageToAction MTA = new MessageToAction();
MTA.MakeAction(result);
}
The message from PubNub differes a little bit from the one that I created manually:
[{\"action\":\"turncompleted\",\"messageID\":\"123123123\",\"playerID\":\"100000067174580\",\"round\":1,\"answers\":[{\"longitude\":21.09375,\"latitude\":24.527134822598},{\"longitude\":1.40625,\"latitude\":23.885837699862}]},\"13926740640746402\",\"chinese-jefecito\"]
I tried to remove the brackets and the slashes the text but then the slashes around the "values" values also got replaces.
I was wondering what I'm doing wrong here?
Here is the action class as well:
class Action
{
[JsonProperty("action")]
public string action { get; set; }
[JsonProperty("messageID")]
public string messageID { get; set; }
[JsonProperty("gameID")]
public string gameID { get; set; }
[JsonProperty("invitorFacebookID")]
public string invitorFacebookID { get; set; }
[JsonProperty("gametype")]
public string gametype { get; set; }
[JsonProperty("numberOfPlayers")]
public string numberOfPlayers { get; set; }
//public List<string> longitude { get; set; }
//public List<string> latitude { get; set; }
//public List<string> values { get; set; }
[JsonProperty("players")]
public List<Players> players { get; set; }
//Should be empty and removed!
[JsonProperty("values")]
public List<Value> values { get; set; }
public Action() { }
}
class Players
{
//Players
[JsonProperty("playerID")]
public string playerID { get; set; }
[JsonProperty("facebookID")]
public string facebookID { get; set; }
}
class Value
{
//Answers
[JsonProperty("longitude")]
public string longitude {get; set;}
[JsonProperty("latitude")]
public string latitude { get; set; }
}
Thanks in advance,
Tomas
Alright, rather than offering corrections I'll just give you the code I would use. Note the sample json you posted is not valid. I'm removing this part; \"13926740640746402\",\"chinese-jefecito\"] and closing the array of Action objects there. You can't have keys on their own in json (both those are keys without values) and also they're in the array rather than within an object. Anyway, here is the json I'm using;
[{\"action\":\"turncompleted\",\"messageID\":\"123123123\",\"playerID\":\"100000067174580\",\"round\":1,\"answers\":[{\"longitude\":21.09375,\"latitude\":24.527134822598},{\"longitude\":1.40625,\"latitude\":23.885837699862}]}]
public class Action
{
public string action { get; set; }
public string messageID { get; set; }
public string round { get; set; }
public Answer[] answers { get; set; }
}
public class Answer
{
public string longitude { get; set; }
public string latitude { get; set; }
}
Action[] actions = JsonConvert.DeserializeObject<Action[]>(jsonString);

Categories