MVC WEB API Controller C# JSON Deserialize not working - c#

I have been struggling with my first c# project. This is a web api controller that will receive a post from AngularJS. The post is coming across but appears to have an extra set of brackets in the JSON object (right click/copy value in vs 2015) . I have tried various methods but everytime I deserialize the JSON object I get null values.
public class LocationsTestController : ApiController
{
[System.Web.Http.HttpPost]
[Route("")]
public IHttpActionResult Post(object json)
{
string sjson = json.ToString();
Coords oCoords = JsonConvert.DeserializeObject<Coords>(sjson);
DBEntities db = new DBEntities();
db.spUpdateLocation(User.Identity.Name, oCoords.latitude.ToString(), oCoords.longitude.ToString());
db.SaveChanges();
return Ok(oCoords.latitude); //return trash data for now
}
}
Here is my JSON copied from the the object received by the post.
{{
"coords": {
"latitude": 43.445969749565833,
"longitude": -80.484091512936885,
"altitude": 100,
"accuracy": 150,
"altitudeAccuracy": 80,
"heading": 38,
"speed": 25
},
"timestamp": 1442113213418
}}
I have tried mapping to the entity framework, but problem is I need to add the authenticated username to the json object as I don't want to trust what is being passed to the API.
Any help would be much appreciated.

Try to receive a model instead of plain string in your WebApi method:
public class CoordsItemModel
{
public double latitude { get; set; }
public double longitude { get; set; }
public int altitude { get; set; }
public int accuracy { get; set; }
public int altitudeAccuracy { get; set; }
public int heading { get; set; }
public int speed { get; set; }
}
public class CoordsModel
{
public CoordsItemModel coords { get; set; }
public long timestamp { get; set; }
}
[System.Web.Http.HttpPost]
[Route("")]
public IHttpActionResult Post(CoordsModel model)
{
DBEntities db = new DBEntities();
db.spUpdateLocation(User.Identity.Name, model.coords.latitude.ToString(), model.coords.longitude.ToString());
db.SaveChanges();
return Ok(model.coords.latitude.ToString()); //return trash data for now
}

There might be some issues with the way you are posting from client side. It's hard to check without the client code and what exactly is coming over network (in fiddler for example).
Generally the web api should be able to get the object directly without you deserializing it. So, if the client is posting proper json, this should work
public IHttpActionResult Post(Coords oCoords)
{
//use oCoords directly
}
If that doesn't work, try changing your web api method to receive string rather than an object, and deserialize that string.
public IHttpActionResult Post(string jsonString)
{
Coords oCoords = JsonConvert.DeserializeObject<Coords>(jsonString);
//rest of the code
}
If you still have double braces, you can do this before you deserialize
jsonString = jsonString.Replace("{{", "{").Replace("}}", "}");
But, obviously, this is not the correct fix. The issue still remains somewhere.

Use It.
public class coordsSample
{
public string latitude { get; set; }
public string longitude { get; set; }
public int altitude { get; set; }
public int accuracy { get; set; }
public int altitudeAccuracy { get; set; }
public int heading { get; set; }
public int speed { get; set; }
}
public class coords1
{
public coordsSample coords { get; set; }
public long timestamp { get; set; }
}
static void Main(string[] args)
{
var jsonFormat = #"[{""timestamp"":""1442113213418"",""coords"":{
""latitude"":""43.445969749565833"",""longitude"":""-80.484091512936885"",""altitude"":""100"",""accuracy"":""150""
,""altitudeAccuracy"":""80"",""heading"":""38"",""speed"":""25""}}]";
var result = JsonConvert.DeserializeObject<coords1>(jsonFormat.Substring(1).Substring(0, jsonFormat.Length - 2));
Console.WriteLine(result.coords.latitude);
Console.WriteLine(result.coords.longitude);
}
Try Like that it will help for you.because those coords you take in json it trated as a properties so for that you need to create a new class and assign this properties in inside it.Thanks

Related

Saving JSON to DataTable

I need to save data retrieved from API to a DataTable. JSON which is returned from API can't be deserialized directly to DataTable using this code:
DataTable dt = (DataTable)JsonConvert.DeserializeObject(json, (typeof(DataTable)));
I got an error: Unexpected JSON token when reading DataTable. I read that it's beacuse JSON format is not as it should be. Mine is as follows:
{
"page": 1,
"page_size": 1000,
"items": [
{
"id": "e1b019b9a8bf408c9cb964c29e845104",
"asset_id": "5adb0d87882b4e14b99bde74a967e84c",
"alias": "Concrete Pump Yellow",
"serial_number": "QEQ000123",
"model": {
"name": "Pump C50-HP"
},
"operating_hours": {
"hours": 100,
"unit_driven": true
}
}
]
}
I know I need format like [{..}] but can't find workaround, API returns JSON as above. I can deserialize it using this:
var obj = JsonConvert.DeserializeObject(json);
but how can I now add data to DataTable? I'm looking for a solution for it
What the JsonConvert class does is it materializes your string version of the response into an object. For this to work, your string version has to match the structure of the resulting object or the class needs hints to know how to inflate the object. The runtime is telling you that there is a mismatch and it doesn't know how to resolve it.
There are a few ways to get this done. I prefer an structured approach so I would recommend you create classes to receive the data:
var payload = #"{
""page"": 1,
""page_size"": 1000,
""items"": [
{
""id"": ""e1b019b9a8bf408c9cb964c29e845104"",
""asset_id"": ""5adb0d87882b4e14b99bde74a967e84c"",
""alias"": ""Concrete Pump Yellow"",
""serial_number"": ""QEQ000123"",
""model"": {
""name"": ""Pump C50-HP""
},
""operating_hours"": {
""hours"": 100,
""unit_driven"": true
}
}
]
}";
public class ApiResponse
{
[JsonProperty("page")]
public int Page { get; set; }
[JsonProperty("page_size")]
public int PageSize { get; set; }
[JsonProperty("items")]
public IEnumerable<ApiResponseItem> Items { get; set; }
}
public class ApiResponseItem
{
[JsonProperty("id")]
public string Id { get; set; }
[JsonProperty("asset_id")]
public string AssetId { get; set; }
[JsonProperty("alias")]
public string Alias { get; set; }
[JsonProperty("serial_number")]
public string SerialNumber { get; set; }
[JsonProperty("model")]
public ApiResponseModel Model { get; set; }
[JsonProperty("operating_hours")]
public ApiResponseOperatingHours OperatingHours { get; set; }
}
public class ApiResponseModel
{
[JsonProperty("name")]
public string Name { get; set; }
}
public class ApiResponseOperatingHours
{
[JsonProperty("hours")]
public string Hours { get; set; }
[JsonProperty("unit_driven")]
public bool UnitDriven { get; set; }
}
var response = JsonConvert.DeserializeObject<ApiResponse>(payload);
As you can see, the classes use hint attributes to let the deserializer know about the fields. You can then loop through the response.Items enumerable and consume the items as desired.
UPDATE:
For posterity and at the suggestion of #mason, it's important to point out that there is no need to use a DataTable. A quick inspection of the payload reveals the output is a paged version of set of records so it's not equivalent to a data table.
Your issue here is that the json you're deserializing is not a DataTable, its just an Object.
JsonConvert.DeserializeObject(request, typeof(Object)) -> Where Object would be a defined Class with parameter definitions to deserialize the json to, i.e page, page_size, id etc..
Once in this format its fairly easy to coerce it into a DataTable:
https://learn.microsoft.com/en-us/dotnet/api/system.data.datatable?view=net-6.0
The Classes would look something along the lines of:
public class Items
{
public Guid? Id {get;set;}
public Guid? AssetId {get;set;}
public string alias {get;set;}
public string serial_number {get;set;}
public Model model {get;set;}
public OperatingHours operatingHours {get;set;}
}
public class Model
{
public string Name { get;set;}
}
public class OperatingHours
{
public int Hours {get;set;}
public bool Unit_Driven {get;set;}
}
public class OverallObject
{
public int Page {get;set;}
public int PageSize {get;set;}
public List<Items> AllItems {get;set;}
}

.NET Core API REST C# List into List is null

I'm developing an api in net core.
I've done a post function in which I send an object containing multiple parameters and a list within another list.
When I'm debugging the code the function is called correctly but I find that the second list always arrives null.
The rest of the data arrives at you correctly. I have done different tests with other objects and everything works correctly.
It is this case in which the list within another the second one arrives null.
My code:
example request input
{
"Name": "TestName",
"Related1":
[{
"id1": "TestNameRelated1",
"Related2":
[{
"id2": "TestNameRelated2"
}]
}]
}
[HttpPost]
public resultExample Test([FromBody]TestClass test)
{
//do something
}
[DataContract]
public class TestClass
{
[DataMember]
public string Name { get; set; }
[DataMember]
public List<TestClassArray> Related1 { get; set; }
}
[DataContract]
public class TestClassArray
{
[DataMember]
public string id1 { get; set; }
[DataMember]
public List<TestClassArray2> Related2 { get; set; }
}
[DataContract]
public class TestClassArray2
{
[DataMember]
public string id2 { get; set; }
}
This api was previously made in .NET framework 4.8 and this case worked correctly.
Now I'm passing the api to .Net5.
Could it be that in .Net5 it is not allowed to pass lists within other lists?
Do you have to enable some kind of configuration to be able to do this now?
You need use class/DTO with constructor like shown below and you should be good to go. I have uploaded this sample API app's code working with .net5.0 on my GitHub here.
public class TestClass
{
public TestClass()
{
Related1 = new List<TestClassArray>();
}
public string Name { get; set; }
public List<TestClassArray> Related1 { get; set; }
}
public class TestClassArray
{
public TestClassArray()
{
Related2 = new List<TestClassArray2>();
}
public string id1 { get; set; }
public List<TestClassArray2> Related2 { get; set; }
}
public class TestClassArray2
{
public string id2 { get; set; }
}
public class ResultExample
{
public string StatusCode { get; set; }
public string Message { get; set; }
}
Controller Post Method
[HttpPost]
[ProducesResponseType(typeof(ResultExample), 200)]
public ResultExample Post([FromBody] TestClass test)
{
ResultExample testResult = new ResultExample();
TestClass test2 = new TestClass();
TestClassArray testClassArray = new TestClassArray();
TestClassArray2 testClassArray2 = new TestClassArray2();
test2.Name = test.Name;
foreach (var item in test.Related1)
{
foreach (var item2 in item.Related2)
{
testClassArray2.id2 = item2.id2;
}
testClassArray.Related2.Add(testClassArray2);
}
test2.Related1.Add(testClassArray);
Console.WriteLine(test2);
testResult.Message = "New Result added successfullly....";
testResult.StatusCode = "201";
return testResult;
}
Swagger Input Sample Payload
Post Controller Result
Response of Sample input payload,(You can change it to default 201 response code as well)
I had a similar issue.
API method shows List was null
In my case a date field was not well formatted
So I use SimpleDateFormat on Android Studio with a correct datetime format
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss",Locale.US);
item.setDate(dateFormat.format(calendar.getTime()));
and works fine

C# Deserialize JSON Object [duplicate]

This question already has answers here:
How to auto-generate a C# class file from a JSON string [closed]
(3 answers)
Closed 3 years ago.
I am attempting to deserialize a Json object that was returned from a web API with the structure as follows.
Here is my class structure in which the object is to be Deserialized into...
public class CandidateJson
{
public string response { get; set; }
//public string result { get; set; }
public Result result { get; set; }
public string Candidates { get; set; }
public List<row> rows { get; set; }
}
public class Result
{
public string result { get; set; }
public string uri { get; set; }
}
public class row
{
public string no { get; set; }
public List<FL> FL { get; set; }
}
public class FL
{
public string val { get; set; }
public string content { get; set; }
}
I am using the following line of code to Deserialized with no success....
var json = JsonConvert.DeserializeObject<CandidateJson>(JsonResult);
Upon execution of this line of code, I am prompted with the following error...
Unexpected character encountered while parsing value: {. Path 'response', line 1, position 13.
I would appreciate any assistance with this issue.
Please let me know if any additional information is needed.
Here is the raw JSON string:
{"response":{"result":{"Candidates":{"row":[
{"no":"1","FL":[{"val":"CANDIDATEID","content":"508304000012555617"},{"val":"Candidate ID","content":"ZR_129661_CAND"},{"val":"First Name","content":"PRODUCTION"},{"val":"Last Name","content":"TEST"},{"val":"Email","content":"patricia.conley#ampcorporate.com"},{"val":"Phone","content":"815-543-2109"},{"val":"Mobile","content":"815-555-5555"},{"val":"Street","content":"555 Test Ave"},{"val":"City","content":"DeKalb"},{"val":"State","content":"IL"},{"val":"Zip Code","content":"60115"},{"val":"SMCREATORID","content":"508304000000490014"},{"val":"Created By","content":"AMP Support IT Team"},{"val":"MODIFIEDBY","content":"508304000000227003"},{"val":"Modified By","content":"Nikki Bowman"},{"val":"Created Time","content":"2019-12-17 08:38:25"},{"val":"Updated On","content":"2019-12-20 15:23:10"},{"val":"Last Activity Time","content":"2019-12-20 15:23:10"},{"val":"SMOWNERID","content":"508304000000490014"},{"val":"Candidate Owner","content":"AMP Support IT Team"},{"val":"Source","content":"Non-Employee Referral"},{"val":"Email Opt Out","content":"false"},{"val":"Is Locked","content":"false"},{"val":"Is Unqualified","content":"false"},{"val":"Is Attachment Present","content":"false"},{"val":"Candidate Status","content":"Sales Training Scheduled"},{"val":"Career Page Invite Status","content":"0"},{"val":"Extension","content":"5555"},{"val":"Sales Training Date_ID","content":"508304000011808848"},{"val":"Sales Training Date","content":"2019-12-11 Digital Sales Training"},{"val":"Start Date","content":"2019-12-17"},{"val":"Candidate Job Category","content":"Print + Digital Outside"},{"val":"District Sales Manager","content":"Luke Wasowski"},{"val":"College Graduate","content":"false"},{"val":"Recruiter Initials","content":"NKB"},{"val":"Unit/Apt/Ste","content":"Apt 5"},{"val":"Hourly Rate","content":"5.00"},{"val":"Work State","content":"Illinois"},{"val":"Full Time/Part Time","content":"FTR"},{"val":"Work Email Address","content":"Nikki.Bowman#ampcorporate.com"},{"val":"EEO Class","content":"1.1"}]},
{"no":"2","FL":[{"val":"CANDIDATEID","content":"508304000011834365"},{"val":"Candidate ID","content":"ZR_125018_CAND"},{"val":"First Name","content":"Jennifer"},{"val":"Last Name","content":"Pedersen"},{"val":"Email","content":"jennyped248_hwo#indeedemail.com"},{"val":"Mobile","content":"+18157517187"},{"val":"City","content":"Genoa"},{"val":"State","content":"IL"},{"val":"Zip Code","content":"60135"},{"val":"Country","content":"United States"},{"val":"Experience in Years","content":"8"},{"val":"Current Employer","content":"WALMART"},{"val":"Current Job Title","content":"MOD TEAM MEMBER"},{"val":"Skill Set","content":"quick and exceptional customer experience, Helping and Advising Customers, Basic Word Processing, Communication Skills, Customer Service, Data Entry, Hard-Working, Intermediate Word Processing, Organisational Skills, Teamwork, Time Management, outstanding communication skills, Microsoft Word, Microsoft Excel, Microsoft Excel 2000, Microsoft Office, Microsoft Outlook, Microsoft PowerPoint, basic scheduling"},{"val":"SMCREATORID","content":"508304000000562001"},{"val":"Created By","content":"Matt Chenoweth"},{"val":"MODIFIEDBY","content":"508304000008810064"},{"val":"Modified By","content":"HR Department"},{"val":"Created Time","content":"2019-12-02 12:25:53"},{"val":"Updated On","content":"2019-12-12 09:04:51"},{"val":"Last Activity Time","content":"2019-12-12 09:04:51"},{"val":"SMOWNERID","content":"508304000000562001"},{"val":"Candidate Owner","content":"Matt Chenoweth"},{"val":"Source","content":"Indeed Resume"},{"val":"Email Opt Out","content":"false"},{"val":"Is Locked","content":"false"},{"val":"Is Unqualified","content":"false"},{"val":"Is Attachment Present","content":"true"},{"val":"Candidate Status","content":"Hired - AMP Office"},{"val":"Career Page Invite Status","content":"0"},{"val":"Source By","content":"Applied by Candidate"},{"val":"EMPID","content":"JFP147"},{"val":"Candidate Job Category","content":"Office - Digital Verification"},{"val":"College Graduate","content":"false"}]
}]}}
,"uri":"/recruit/private/json/Candidates/searchRecords"}}
I haven't tested it, but by the looks of it, your code should look like:
public class CandidateJson
{
public Response response { get; set; }
}
public class Response
{
public Result result { get; set; }
public string uri { get; set; }
}
public class Result
{
public Candidate Candidates { get; set; }
}
public class Candidate
{
public List<Row> row { get; set; }
}
public class Row
{
public string no { get; set; }
public List<FL> FL { get; set; }
}
public class FL
{
public string val { get; set; }
public string content { get; set; }
}
Note: You might want to use int or decimal instead of string for val and no, but there is not enough information for me to assert that.

Json Value doesn't assign to the List [HttpPost]

Since am new to web api, i am finding some difficulty to post json List to Web API.
Json
[
{
"ItemId":20,
"RegId":"VISIT0001778",
"BLoadDetailId":"8/31/2018 12:28:10 PM",
"OrderReferenceNo":null,
"StartTime":"0001-01-01T00:00:00",
"InvalidItemMsg":"",
"InvalidItemstatus":false,
"BLoadingBay":"Chute 009",
"BLoadingBayCode":null,
"BLoadingBayID":7,
"RFID":7123,
"GangId":2,
"BOrderTransfer":false,
"BLoadedBags":0.0,
"BRemainingBags":0.0,
"BConversionValue":null,
"WHid":2
}
]
class :
public class clsStartTimeUpdate
{
public int ItemId { get; set; }
public string RegId { get; set; }
public string BLoadDetailId { get; set; }
public string OrderReferenceNo{ get; set; }
public DateTime StartTime { get; set; }
public string InvalidItemMsg { get; set; }
public bool InvalidItemstatus { get; set; }
public string BLoadingBay { get; set; }
public string BLoadingBayCode { get; set; }
public int? BLoadingBayID { get; set; }
public long? RFID { get; set; }
public int? GangId { get; set; }
public bool BOrderTransfer { get; set; }
public decimal BLoadedBags { get; set; }
public decimal BRemainingBags { get; set; }
public string BConversionValue { get; set; }
public int? WHid { get; set; }
}
Json request
http://localhost:49290/api/config/Post?StartTimeDetails=[enter image description here][1][{%22ItemId%22:20,%22RegId%22:%22VISIT0001778%22,%22BLoadDetailId%22:%228/31/2018%2012:28:10%20PM%22,%22OrderReferenceNo%22:null,%22StartTime%22:%222001-01-01T00:00:00%22,%22InvalidItemMsg%22:%22%22,%22InvalidItemstatus%22:false,%22BLoadingBay%22:%22Chute%20009%22,%22BLoadingBayCode%22:null,%22BLoadingBayID%22:7,%22RFID%22:7123,%22GangId%22:2,%22BOrderTransfer%22:false,%22BLoadedBags%22:0.0,%22BRemainingBags%22:0.0,%22BConversionValue%22:null,%22WHid%22:2}]
Method WebAPI
[HttpPost]
public HttpResponseMessage Post([FromUri]List<clsStartTimeUpdate> StartTimeDetails)
{
return base.BuildSuccessResult(HttpStatusCode.OK, StartTimeDetails);
}
result:
[{"ItemId":0,"RegId":null,"BLoadDetailId":null,"OrderReferenceNo":null,"StartTime":"0001-01-01T00:00:00","InvalidItemMsg":null,"InvalidItemstatus":false,"BLoadingBay":null,"BLoadingBayCode":null,"BLoadingBayID":null,"RFID":null,"GangId":null,"BOrderTransfer":false,"BLoadedBags":0.0,"BRemainingBags":0.0,"BConversionValue":null,"WHid":null}]
return result doesnot assign the values as in the Json.
May be this is a simple situation , but i really appreciate the help.
It seems that you want to convey your json with HttpGet request instead of HttpPost then you can follow below,
1) Send Json with HttpGet
Method: Get
Url: http://localhost:49290/api/config/MyGet?StartTimeDetails=[{%22ItemId%22:20,%22RegId%22:%22VISIT0001778%22,%22BLoadDetailId%22:%228/31/2018%2012:28:10%20PM%22,%22OrderReferenceNo%22:null,%22StartTime%22:%220001-01-01T00:00:00%22,%22InvalidItemMsg%22:%22%22,%22InvalidItemstatus%22:false,%22BLoadingBay%22:%22Chute%20009%22,%22BLoadingBayCode%22:null,%22BLoadingBayID%22:7,%22RFID%22:7123,%22GangId%22:2,%22BOrderTransfer%22:false,%22BLoadedBags%22:0.0,%22BRemainingBags%22:0.0,%22BConversionValue%22:null,%22WHid%22:2}]
Web Api Method:
[HttpGet]
public HttpResponseMessage MyGet(string StartTimeDetails)
{
List<clsStartTimeUpdate> clsStartTimeUpdates = JsonConvert.DeserializeObject<List<clsStartTimeUpdate>>(StartTimeDetails);
return base.BuildSuccessResult(HttpStatusCode.OK, StartTimeDetails);
}
Note: Its bad practice to send huge json in query string, so for use HttpPost instead
2) Send Json with HttpPost
Method: Post
Url: http://localhost:49290/api/config/MyPost
Data:
[
{
"ItemId":20,
"RegId":"VISIT0001778",
"BLoadDetailId":"8/31/2018 12:28:10 PM",
"OrderReferenceNo":null,
"StartTime":"0001-01-01T00:00:00",
"InvalidItemMsg":"",
"InvalidItemstatus":false,
"BLoadingBay":"Chute 009",
"BLoadingBayCode":null,
"BLoadingBayID":7,
"RFID":7123,
"GangId":2,
"BOrderTransfer":false,
"BLoadedBags":0.0,
"BRemainingBags":0.0,
"BConversionValue":null,
"WHid":2
}
]
Web Api Method:
[HttpPost]
public HttpResponseMessage MyPost([FromBody]List<clsStartTimeUpdate> StartTimeDetails)
{
return base.BuildSuccessResult(HttpStatusCode.OK, StartTimeDetails);
}
For complex types Always use [FromBody] in the argument.
[HttpPost]
public HttpResponseMessage Post([FromBody]List<clsStartTimeUpdate> StartTimeDetails)
{
return base.BuildSuccessResult(HttpStatusCode.OK, StartTimeDetails);
}
And then specify your query object in Body.
Note: To specify the value in the body, You will need an API client like Postman or Swagger.
https://www.getpostman.com/
In Postman,
Select Post method and specify the URL,
Then go to "Body" tab and select raw.
Specify JSON as type.
In the body, paste your data.
{ [
{
"ItemId":20,
..........
}
]}
The Other answer by #ershoaib is the real fix for the problem that OP is facing. However, I am leaving this answer as it is the standard which should be followed.
Since you are using post you should expect the data in the controller method to come from body. See related issue here

C# Web api getting POST data from JSON

I have an issue that I've been trying to solve. I'm trying to send data from a java application to a web server, but I can't figure out how to actually send it. The java code is as follows:
String hStr = "{\"id\":2,\"name\":\"John\",\"height\":36.72342538,\"width\":2.99999998,\"frequency\":871.07,\\"idList\":[],\"level\":0.0}";
House ap = toJsonMap.readValue(hStr, House.class);
when: "ask the server to add a house from the request"
def response = server.httpClient.requestSpec { spec ->
spec.body { b ->
b.text(hStr)
b.type("application/json")
}
}
.post("//modeling/housing/{hid}/prop/point/in");
I then have the C# read this code like this:
[Route("modeling/housing/{hid}/prop/point/in")]
[HttpPost]
public HttpResponseMessage AddPoint(int hid, int id, string name, double height, double width, double frequency, List<int> idList, double level)
{
DAL.House h = new DAL.House();
try
{
using (DAL.Entities context = DAL.Entities.CreateContextForComplex(said))
{
if (!context.Houses.Where(a => a.Id == id).Any())
{
h.Name = name;
h.Height = height;
h.Width = width;
h.Frequency = frequency;
h.IdList= idList;
h.Level = level;
h.LastModified = System.DateTime.UtcNow;
context.Houses.Add(ap);
context.SaveChanges();
return Request.CreateResponse(HttpStatusCode.OK, ap);
}
else
{
return Request.CreateResponse(HttpStatusCode.InternalServerError, "Housing id already exists");
}
}
}
catch (EntityException)
{
return Request.CreateResponse(HttpStatusCode.InternalServerError, "Entity Exception");
}
catch (Exception ex)
{
return Request.CreateResponse(HttpStatusCode.InternalServerError, ex);
}
}
I just can't figure out how to get the data from this post. Particularly getting all of the different types of variables. I found a lot of different answers, but nothing seems to work.
Most likely you need to create a class that has properties matching the incoming request post body's object properties. For example:
public class House
{
public int Hid { get; set; }
public int Id { get; set; }
public string Name { get; set; }
public double Height { get; set; }
public double Width { get; set; }
public double Frequency { get; set; }
public List<int> IdList { get; set; }
public double Level { get; set; }
}
Then you would update your method signature as follows:
public HttpResponseMessage AddPoint(House house)
Try to create a class that represents all the properties in the JSON Object:
public class YouClass
{
public int Id { get; set; }
public string Name { get; set; }
public string Height { get; set; }
......
// add others
}
Then in your controller:
public class HousingController : ApiController
{
[Route("AddPoint")
[HttpPost]
public HttpResponseMessage AddPoint([FromBody] YourClass)
{
}
}
Then modify the URL of API your are calling:
.post("api/Housing/Addpoint")
Your URL might be different, you might use : http://localhost:Port/api/Housing/Addpoint and the port. Make sure you try it in browser first or use Postman. Check this
.post("//modeling/housing/{hid}/prop/point/in");
This line of code should give you a timeout in your java, if this is exactly how you have it typed. What you really want here is something more like:
.post("http://localhost:PortNumber/modeling/housing/"+ ap.id +"/prop/point/in");
Where PortNumber is the port your web api is running on, and ap.Id is the Id of the record you are trying to modify.
After you have corrected your endpoint situation, then move on to the other answers and use JSON.Net to deserialize your JSON back into a class.

Categories

Resources