how to convert list obj to client.PostAsJsonAsync - c#

how to convert list obj to client.PostAsJsonAsync
Class model
public class CheckStatusModel
{
public int OBJID { get; set; }
public string SUPID { get; set; }
public string STATUSPTC { get; set; }
public int DATEACTIVESUP { get; set; }
}
public class CheckStatus
{
public CheckStatusModel Data { get; set; }
public string StatusCode { get; set; }
}
Sending request to find web api REST service resource using
HttpClient**
using (var client = new HttpClient())
{
client.BaseAddress = new Uri(Baseurl);
client.DefaultRequestHeaders.Clear();
client.DefaultRequestHeaders.Accept.Add(new
MediaTypeWithQualityHeaderValue("application/json"));
HttpResponseMessage response = await client.PostAsJsonAsync("api/RPDeployment/BIL_CFP_BOX_CHECK_STATUSPTC", checkStatusParam);
if(response.IsSuccessStatusCode)
{
var EmpResponse = response.Content.ReadAsStringAsync().Result;
ListStatusPTC = JsonConvert.DeserializeObject<List<CheckStatus>>(EmpResponse);// not convert ????
}
}
EmpResponse
{
"data": [**
{
"OBJID": 1012540462,
"SUPID": 1041252952,
"STATUSPTC": 1,
"DATEACTIVESUP": 0
}
**],
"StatusCode": 200
}
help me please ??

Oh I see. You're trying to deserialize an object (denoted by { and }) into a list (in JSON, denoted by [ and ]).
You need to change your CheckStatus class as follows:
public class CheckStatus
{
public List<CheckStatusModel> Data { get; set; } // data is an array so this needs to be some kind of collection
public string StatusCode { get; set; }
}
And deserialize like so:
ListStatusPTC = JsonConvert.DeserializeObject<CheckStatus>(EmpResponse); // the JSON contains an object, so this needs to deserialize to an object. you can't deserialize to a list.

Related

Deserialize a JSON object Inside of an Array/Square brackets

I am trying to consume API receiving JSON objects. The problem is my API sends these objects nested in square brackets, which makes me deseralize it as a List instead of a single object.
I am declaring this variable as an array of this instance of the class.
SomeModel[] variable = new SomeModel[1];
using (var httpClient = new HttpClient())
{
using (var response = await httpClient.GetAsync("https://someurl.dev.local/getInfo/" + id))
{
if (response.StatusCode == System.Net.HttpStatusCode.OK)
{
string apiResponse = await response.Content.ReadAsStringAsync();
variable = JsonConvert.DeserializeObject<SomeModel[]>(apiResponse);
}
else
ViewBag.StatusCode = response.StatusCode;
}
}
Thiis is a sample of a JSON object I should be receiving, which I tested using Postman:
[
{
"pri_key": "7005210446", //concatenation of this_nbr & that_nbr
"dl_load_date": "2021-11-25T00:00:00Z",
"this_nbr": 7005210,
"that_nbr": 446,
"Passtest": "Eligible"
}
]
...And this is SomeModel class:
namespace ThisSolution.Models
{
public partial class SomeModel
{
public DateTime? DlLoadDate { get; set; }
public int? ThisNbr{ get; set; }
public int? ThatNbr { get; set; }
public string Passtest { get; set; }
public string PriKey { get; set; }
}
}
I am getting is this error:
JsonReaderException: Unexpected character encountered while parsing value: <. Path '', line 0, position 0.
How can I deserialize or is something wrong in my code?
You need to fix your model
public partial class SomeModel
{
[JsonProperty("pri_key")]
public string PriKey { get; set; }
[JsonProperty("dl_load_date")]
public DateTimeOffset DlLoadDate { get; set; }
[JsonProperty("this_nbr")]
public int? ThisNbr { get; set; }
[JsonProperty("that_nbr")]
public int? ThatNbr { get; set; }
[JsonProperty("Passtest")]
public string Passtest { get; set; }
}

Json Deserialise return null when convert to list of object in c# [duplicate]

This question already has answers here:
Private setters in Json.Net
(5 answers)
Closed 4 years ago.
I am trying to deserialise the json into custom class list using Newtonsoft.Json.
Here is my code:
public List<EmployeeModel> getEmployee()
{
string Baseurl = "http://dummy.restapiexample.com/api/v1/";
using (var client = new HttpClient())
{
//Passing service base url
client.BaseAddress = new Uri(Baseurl);
client.DefaultRequestHeaders.Clear();
//Define request data format
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
//Sending request to find web api REST service resource GetAllEmployees using HttpClient
var EmpResponse = new List<EmployeeModel>();
var Res = client.GetAsync("employees");
Res.Wait();
var result = Res.Result;
//Checking the response is successful or not which is sent using HttpClient
if (result.IsSuccessStatusCode)
{
//Storing the response details recieved from web api
var r = result.Content.ReadAsStringAsync().Result;
EmpResponse = JsonConvert.DeserializeObject<List<EmployeeModel>>(r);
//Deserializing the response recieved from web api and storing into the Employee list
}
//returning the employee list to view
return EmpResponse;
}
}
When I check the variable r value I am getting following Json String:
[
{
"id": "317",
"employee_name": "Nitza",
"employee_salary": "775",
"employee_age": "1",
"profile_image": ""
},
{
"id": "318",
"employee_name": "Nitza Ivri",
"employee_salary": "10000",
"employee_age": "33",
"profile_image": ""
}
]
Also, my model code is as per below:
public class EmployeeModel
{
public string id { get; private set; }
public string employee_name { get; private set; }
public string employee_salary { get; private set; }
public string employee_age { get; private set; }
}
The reason is that your properties in EmployeeModel has private set. You need to remove private from your properties then it would be able to deserialize successfully. Your entity should be like following:
public class EmployeeModel
{
public string id { get; set; }
public string employee_name { get; set; }
public string employee_salary { get; set; }
public string employee_age { get; set; }
}
Also, your EmployeeModel does not contain property profile_image. You need to add this property to your model.
If it is important for you to keep your properties setters as private, you can provide a constructor that has parameters like:
public class EmployeeModel
{
public EmployeeModel(string id, string employee_name,string employee_salary, string employee_age, string profile_image )
{
this.id = id;
this.employee_name = employee_name;
this.employee_salary = employee_salary;
this.employee_age = employee_age;
this.profile_image = profile_image;
}
public string id { get; private set; }
public string employee_name { get; private set; }
public string employee_salary { get; private set; }
public string employee_age { get; private set; }
public string profile_image { get; private set; }
}

How to convert JArray to generic List<>

Via an http Post, I send html FormData to my Web Api2 controller.
The FormData contains one or more images, as well as client properties.
My front end Angular 5 service sends the http post (working fine):
var url = this.host + 'import/MediaUpload';
return this.http.post(url, formData, options)
.map((result: any) => result._body)
.catch(this.handleError);
I would like to convert the FormData to a generic List of MediaInfo class (defined below this MediaUpload() method) :
public async Task<HttpResponseMessage> MediaUpload(int projectId, int sectionId)
{
// Check if the request contains multipart/form-data.
if (!Request.Content.IsMimeMultipartContent())
{
throw new HttpResponseException(HttpStatusCode.UnsupportedMediaType);
}
var provider = await Request.Content.ReadAsMultipartAsync<InMemoryMultipartFormDataStreamProvider>(new InMemoryMultipartFormDataStreamProvider());
//access form data
NameValueCollection formData = provider.FormData;
List<MediaInfo> listMedia = new List<MediaInfo>();
//dynamic jsonData = JObject.Parse(formData["MediaInfo"]); // THROWS ERROR
JArray ary = JArray.Parse(formData["MediaInfo"]);
foreach (var item in ary) {
//listMedia.Add((MediaInfo)item); // ???
Console.WriteLine(item);
}
//access files
IList<HttpContent> files = provider.Files;
HttpContent file1 = files[0];
var thisFileName = file1.Headers.ContentDisposition.FileName.Trim('\"');
// additional file upload code removed, working fine..
var response = Request.CreateResponse(HttpStatusCode.OK);
response.Headers.Add("DocsUrl", URL);
return response;
}
public class MediaInfo
{
public string PatientID { get; set; }
public string PatientFirstName { get; set; }
public string PatientLastName { get; set; }
public string PatientUID { get; set; }
public string PatientDOB { get; set; }
public string ExamDate { get; set; }
public string ExamDevice { get; set; }
public string SerialNo { get; set; }
public string Eye { get; set; }
public int DeviceID { get; set; }
public int CSIInstanceID { get; set; }
public int MediaNo { get; set; }
public string Procedure { get; set; }
public string FileName { get; set; }
public int FileSize { get; set; }
}
I thought I could do something like :
listMedia.Add((MediaInfo)item;
But I'm missing the correct conversion somewhere.
You can convert a JObject to a type of your choosing with the .ToObject<T>() method.
https://www.newtonsoft.com/json/help/html/M_Newtonsoft_Json_Linq_JToken_ToObject__1_1.htm
In this case you want your code to look like this:
listMedia.Add(item.ToObject<MediaInfo>());
You could also use JsonConvert.DeserializeObject to convert it directly into the desired type provided formData["MediaInfo"] returned well formed JSON.
List<MediaInfo> listMedia = JsonConvert.DeserializeObject<List<MediaInfo>>(formData["MediaInfo"]);

JSON to object C# (mapping complex API response to C# object)

I am able to handle simple JSON serialization and deserialization but this API response seems little complicated, and I am seeking an advice as to what would be ideal approach to tackle this.
I'm trying to call an API for MVC application.
Goal is to map API data to model.
API endpoint is
https://www.alphavantage.co/query?function=TIME_SERIES_INTRADAY&symbol=MSFT&interval=1min&apikey=MyAPIKey
Troubles here are:
JSON data keys have white space in them.
When I tried doing paste special in Visual studio, It gave me a long
list of classes for each date entry separately, because this API
call returns a separate set of information for date.
To solve problem explained in point 1, I used [JsonProperty("1. Information")] in class. And in my code..
public async Task TSI()
{
HttpClient client = new HttpClient();
//Uri uri = new Uri("http://date.jsontest.com/");
Uri uri = new Uri("https://www.alphavantage.co/query?function=TIME_SERIES_INTRADAY&symbol=MSFT&interval=5min&apikey=demo");
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
HttpResponseMessage response = await client.GetAsync(uri);
if (response.IsSuccessStatusCode)
{
dynamic result = await response.Content.ReadAsAsync<object>();
IEnumerable<dynamic> dObj = JsonConvert.DeserializeObject<dynamic>(result.ToString());
IEnumerable<dynamic> t1 = dObj.FirstOrDefault();
IEnumerable<dynamic> t2 = dObj.LastOrDefault();
dynamic MetaData = t1.FirstOrDefault();
Rootobject ro = new Rootobject();
ro.MetaData = MetaData;
}
PS: I'm relatively new to make API calls and handling them.
I was able to make a call to
date.jsontest.com
and map the API data to model (which I had created using paste special)
//API response
{
"time": "12:53:22 PM",
"milliseconds_since_epoch": 1504875202754,
"date": "09-08-2017"
}
//C# code to map to API data
public class sampleObject
{
public string time { get; set; }
public long milliseconds_since_epoch { get; set; }
public string date { get; set; }
}
My RootObject looks like this:
public class Rootobject
{
[JsonProperty("Meta Data")]
public MetaData MetaData { get; set; }
[JsonProperty("Time Series (1min)")]
public TimeSeries1Min TimeSeries1min { get; set; }
}
public class MetaData
{
[JsonProperty("1. Information")]
public string _1Information { get; set; }
[JsonProperty("2. Symbol")]
public string _2Symbol { get; set; }
[JsonProperty("3. Last Refreshed")]
public string _3LastRefreshed { get; set; }
[JsonProperty("4. Interval")]
public string _4Interval { get; set; }
[JsonProperty("5. Output Size")]
public string _5OutputSize { get; set; }
[JsonProperty("6. Time Zone")]
public string _6TimeZone { get; set; }
}
// I have so many of these sub-classes for dates, which again is an issue
public class TimeSeries1Min
{
public _20170907160000 _20170907160000 { get; set; }
public _20170907155900 _20170907155900 { get; set; }
....
....}
public class _20170907160000
{
public string _1open { get; set; }
public string _2high { get; set; }
public string _3low { get; set; }
public string _4close { get; set; }
public string _5volume { get; set; }
}
public class _20170907155900
{
public string _1open { get; set; }
public string _2high { get; set; }
public string _3low { get; set; }
public string _4close { get; set; }
public string _5volume { get; set; }
}
It is hard to create a model from this json, but you can convert those data to dictionary
var jObj = JObject.Parse(json);
var metadata = jObj["Meta Data"].ToObject<Dictionary<string, string>>();
var timeseries = jObj["Time Series (1min)"].ToObject<Dictionary<string, Dictionary<string, string>>>();
The following code should do what you want
if (response.IsSuccessStatusCode)
{
var result = await response.Content.ReadAsStringAsync();
var obj = JsonConvert.DeserializeObject<Rootobject>(result);
//No idea what you want to do with this line as there is no MetaData property on the root object
obj.MetaData = MetaData;
}

How do I create a Dictionary<string,string> for nested object

I am retrieving the following JSON via a POST to an API
{
"State":"Andhra_Pradesh",
"District":"Guntur",
"Fact":"SELECT",
"Description":"",
"FactDate":"",
"FactNumber":"",
"FactType":"SELECT",
"Fact":{"Id":"1"}
}
I am able to execute the Ajax request via javascript, but I also want to consume the API through C# code.
I am using the below code, but I'm not quite sure on how to add the Fact object?
var values = new Dictionary<string, string>
{
{ "State", selectedState },
{ "District", selectedDistrict },
{ "Fact", ""},
{ "FactType", ""},
{ "FactNumber", ""},
{ "Description", ""},
{"Fact", "{Id,1}" },
{"FactDate", factDate.Date.ToString() }
};
using (var httpClient = new HttpClient())
{
var content = new FormUrlEncodedContent(values);
var response = await httpClient.PostAsync("http://api.in/" + "test", content);
}
How do I add the Fact object to Dictionary?
You'll probably need to define the data you are sending as actual class before using httpclient.
If you had only name value pairs then you could have used the NameValueCollection and sent as a formurlencoded but since you have a complex type, you might consider this below.
See below.
public class Rootobject
{
public string State { get; set; }
public string District { get; set; }
public Fact Fact { get; set; }
public string Description { get; set; }
public string CaseDate { get; set; }
public string FactNumber { get; set; }
public string FactType { get; set; }
}
public class Fact
{
public string Id { get; set; }
}
Usage is as below. be sure to include a reference to System.Net.Http.Formatting.dll
var client = new HttpClient();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
var model = new Rootobject { State = "Andhra_Pradesh", District = "Guntur", FactType = "SELECT", Description = "", CaseDate = "", FactNumber = "", Fact = new Fact { Id = "1"} };
var data = await client.PostAsJsonAsync("http://api.in/" + "test", model);
I think this is just a json object, you can either create a class which have the same properties of (state, district etc ..) and use json serializer
or you can create JObject using Json.Net
You can use Newtonsonft.Json to to the serializaton/deserialization job and the code will be like that.
public class Rootobject
{
[JsonProperty("State")]
public string State { get; set; }
[JsonProperty("District")]
public string District { get; set; }
[JsonProperty("Fact")]
public Fact Fact { get; set; }
[JsonProperty("Description")]
public string Description { get; set; }
[JsonProperty("CaseDate")]
public string CaseDate { get; set; }
[JsonProperty("FactNumber")]
public string FactNumber { get; set; }
[JsonProperty("FactType")]
public string FactType { get; set; }
}
public class Fact
{
[JsonProperty("Id")]
public string Id { get; set; }
}
And then, after instatiating your object, just serialize it.
Rootobject example = new Rootobject();
//Add values to the variable example.
var objectSerialized = JsonConvert.SerializeObject(example);
After that, you will have a json ready to be send wherever you want.
Just change {"Fact", "{Id,1}" } to {"Fact.Id", "1" },

Categories