Web Service required this format:
{
"Data":"{\"Name\":\"HelloWorld\",\"BirthDate\":\"2020-03-03\",\"BirthPlace\":\"Nowhere\"}"
}
I required above format to post to web service but my code below doesn't fulfil the format. Please help. I've been using below code to post
var Data = JsonConvert.SerializeObject(new
{
Data = new
{
Name= "HelloWorld",
BirthDate = "2020-03-03",
BirthPlace= "Nowhere"
}
});
using (var client = new HttpClient())
{
HttpResponseMessage response = await client.PostAsJsonAsync(apiUrl, Data);
}
If data should contains a string serialization of the real object. You can simply serialize the inner object using the string result as value on your second serialization.
using Newtonsoft.Json;
public static string WrapAndSerialize(object value){
return JsonConvert.SerializeObject(new { Data = JsonConvert.SerializeObject(value) });
}
Using it like:
var myObject=
new
{
Name = "HelloWorld",
BirthDate = "2020-03-03",
BirthPlace = "Nowhere",
};
var Data= WrapAndSerialize(myObject);
using (var client = new HttpClient())
{
HttpResponseMessage response = await client.PostAsJsonAsync(apiUrl, Data);
}
LiveDemo
To get the required format do:
string name = "HelloWorld";
string birthdate = "2020-03-03";
string birthplace= "Nowhere";
var jsonData = JsonConvert.SerializeObject(new
{
Data = $"\"Name\"=\"{name}\",\"BirthDate\"=\"{birthdate}\",\"BirthPlace\"=\"{birthplace}\""
});
See it in action: https://dotnetfiddle.net/UBXDtd
The format states that Data shall contain a string. Your code serializes an object with properties, which results in:
{"Data":{"Name":"HelloWorld","BirthDate":"2020-03-03","BirthPlace":"Nowhere"}}
EDIT: While this works, I would recommend #xdtTransform's answer over this. Leaving this here, in case his solution is for some reason not applicable.
I'm deserializing a JSON using Newtonsoft for my Xamarin application, I am facing some issue when deserializing DateTime.
I have tried using the same code on asp.net C#, and storing the data into a dataset. The C# gave me the right output. However when it goes to Xamarin form, it produces the wrong output.
Expected result should be 2/4/2019 12:00:00 AM.
I have no idea how the 4/1/2019 4:00:00PM came from.
Wrong output using Xamarin
Right output using C#
using Xamarin
public List<GetFleet> GetDefaults(string xUserID)
{
string inJson =
List<GetFleet> tempList = new List<GetFleet>();
try
{
Uri serverUri2 = new Uri(inJson.ToString());
string rs2 = RequestGeoHttpAsString(serverUri2);
DataSet dataSet = JsonConvert.DeserializeObject<DataSet>(rs2);
DataTable dataTable = dataSet.Tables["Table1"];
foreach (DataRow row in dataTable.Rows)
{
tempList.Add(new GetFleet
{
FleetID = row["registrationNumber"].ToString(),
FleetName = row["Location"].ToString(),
FleetIgnition = row["Ignition"].ToString(),
FleetFuel1 = row["sFuel1"].ToString(),
FleetStartTime = row["startTime"].ToString()
});
}
}
catch (Exception ex)
{
string exe = ex.Message;
}
return tempList;
}
using C#
protected void Page_Load(object sender, EventArgs e)
{
string url =
Uri serverUri2 = new Uri(url.ToString());
string rs2 = RequestGeoHttpAsString(serverUri2);
DataSet dataSet = JsonConvert.DeserializeObject<DataSet>(rs2);
DataTable dataTable = dataSet.Tables["Table1"];
string json = JsonConvert.SerializeObject(dataSet, Formatting.Indented);
Response.Write(json);
}
public string RequestGeoHttpAsString(Uri address)
{
string result = "";
// Create the web request
HttpWebRequest request = System.Net.WebRequest.Create(address) as HttpWebRequest;
// Get response
using (HttpWebResponse response = request.GetResponse() as HttpWebResponse)
{
// Get the response stream
StreamReader reader = new StreamReader(response.GetResponseStream());
// Read the whole contents and return as a string
result = reader.ReadToEnd();
}
return result;
}
I used another alternative solution on this matter.
I converted the date into string/VARCHAR in backend.
When it returns in JSON, it would be in text.
How can i get my master_handler method handler_response data to get_data method without using session in C#.
Currently i getting data by using session, i want to get handler_response data in string response under GET_DATA() method without using session.
How can do this please help
My code is
[WebMethod]
public static string GET_DATA()
{
string Search = "1";
master_handler(Search);
string response = string.Empty;
response = (string)HttpContext.Current.Session["HANDLER_RESPONSE"]; // getting handler_response here
HttpContext.Current.Session["obj_GET_FLIGHT_DATA"] = response;
return response;
}
public static string master_handler(string dt)
{
string handler_response= string.Empty;
LibraryCaller.Master_Handler MH = new LibraryCaller.Master_Handler();
string get_api_data = MH.Search(dt);
JObject jObj = JObject.Parse(get_api_data);
handler_response= jObj.ToString();
HttpContext.Current.Session["HANDLER_RESPONSE"] = handler_response; // here currently using sesson
return handler_response;
}
Cache the value instead:
Cache.Insert("HANDLER_RESPONSE", handler_response);
To retrieve it use:
string handler_response;
handler_response = (string)Cache["HANDLER_RESPONSE"];
That's the simplest way to do it via caching, read up on it as theres a lot more to it.
I have done this by using class.
public class handler
{
public string data_handler(string dt)
{
string handler_response= string.Empty;
LibraryCaller.Master_Handler MH = new LibraryCaller.Master_Handler();
string get_api_data = MH.Search(dt);
JObject jObj = JObject.Parse(get_api_data);
handler_response= jObj.ToString();
HttpContext.Current.Session["HANDLER_RESPONSE"] = handler_response; // here currently using sesson
return handler_response;
}
}
and access data
handler h = new handler();
response = h.data_handler(search);
I am trying to pass List as a parameter to web Api , Using below code;
Client Side
public async Task<ActionResult>BatchUpdatePartial(MVCxGridViewBatchUpdateValues<NewWorkItem, int> batchValues)
{
var updatedItems = new List<NewWorkItem>();
string url = "http://localhost:9198/api/values";
foreach (var item in batchValues.Update)
{
if (batchValues.IsValid((item)))
{
var updatedVals = new NewWorkItem();
updatedVals.CPK_ID = item.CPK_ID;
updatedVals.BYR_ID = item.BYR_ID;
updatedVals.P_ID = item.P_ID;
updatedVals.CPK_PRI_FLG = item.CPK_PRI_FLG;
updatedItems.Add(updatedVals);
}
else
batchValues.SetErrorText(item, "Correct Vallidation Errors");
}
using (var client = new WebClient())
{
client.Headers[HttpRequestHeader.ContentType] = "application/json";
client.Encoding = System.Text.Encoding.UTF8;
string serialisedData = JsonConvert.SerializeObject(updatedItems);
string response = client.UploadString(url, serialisedData);
Object result = JsonConvert.DeserializeObject(response);
}
return PartialView("_GridViewPartial", NewWorkItem.GridData);
}
Server Side
public string Post([FromBody]string[] values)
{
string seperator = ",";
string data = string.Join(seperator, values.ToList<string>());
string result = string.Format("Succesfully uploaded: {0}", data);
return result;
}
But I am always getting NULL inside the values at server side ?
Can you please suggest me solution ?
Thanks
Unfortunately, you are not actually sending a string[] the way your POST method expects. You are sending serializedData, which is, by your own definition, a serialization of updatedItems. updatedItems is a list of a reference type - you do not provide the definition of it here, but I guarantee you it is not going to serialize the same way a string does.
You will need to change updatedItems to be List<string> or something similar.
I'm trying to setup a web service in a asp.net project to return requests in a JSON format.
the web service method code is as follows:
public string NavigationItems()
{
using (TTConnection connection = new TTConnection("ClientDb"))
{
if (MySession.Current.MyClub == null)
return USER_ERROR;
MiddleTier.WebNavigation.WebNavigationGenerator gen = MySession.Current.NavGenerator;
List<NavigationElement> list = gen.GetNavigation();
string json = JsonConvert.SerializeObject(list);
return json;
}
}
The NavigationElement object has the following constructor & properties
public NavigationElement(string pUrl, int pSequence, string pLinkText, string pDescription,int pUid)
{
url = pUrl;
sequence = pSequence;
linkText = pLinkText;
description = pDescription;
uid = pUid;
}
and the request returns the following JSON
Content-Type:application/json; charset=utf-8;
{"d":"[{\"elements\":[],\"url\":\"~/Welcome.aspx\",\"sequence\":1,\"linkText\":\"Home\",\"description\":\"Home Page\",\"uid\":1,\"parent\":null},{\"elements\":[],\"url\":\"~/About.aspx\",\"sequence\":2,\"linkText\":\"About\",\"description\":\"About Us\",\"uid\":2,\"parent\":null},{\"elements\":[{\"elements\":[{\"elements\":[],\"url\":\"~/Member/ClubHomeSub/ClubTheme.aspx\",\"sequence\":1,\"linkText\":\"Club Theme\",\"description\":\"Club Theme\",\"uid\":5,\"parent\":null},{\"elements\":[],\"url\":\"~/Member/ClubHomeSub/ClubPages.aspx\",\"sequence\":2,\"linkText\":\"Club Pages\",\"description\":\"Club Pages\",\"uid\":8,\"parent\":null}],\"url\":\"~/Member/ClubHomeSub/ClubAdmin.aspx\",\"sequence\":1,\"linkText\":\"Club Admin\",\"description\":\"Club Admin\",\"uid\":4,\"parent\":null}],\"url\":\"~/Member/ClubHome.aspx\",\"sequence\":3,\"linkText\":\"Club Home\",\"description\":\"Club Home\",\"uid\":3,\"parent\":null},{\"elements\":[],\"url\":\"~/Member/GameAnalysis.aspx\",\"sequence\":4,\"linkText\":\"Game Analysis\",\"description\":\"Game Analysis\",\"uid\":6,\"parent\":null},{\"elements\":[],\"url\":\"~/Member/SkillAquisition.aspx\",\"sequence\":5,\"linkText\":\"Skill Aquisition\",\"description\":\"Learn new game skills\",\"uid\":7,\"parent\":null}]"}
Which is valid but gets interpreted as an object with a very long string
d: "[{"elements":[],"url":"~/Welcome.aspx","sequence":1,"linkText":"Home","description":"Home Page","uid":1,"parent":null},{"elements":[],"url":"~/About.aspx","sequence":2,"linkText":"About","description":"About Us","uid":2,"parent":null},{"elements":[{"elements":[{"elements":[],"url":"~/Member/ClubHomeSub/ClubTheme.aspx","sequence":1,"linkText":"Club Theme","description":"Club Theme","uid":5,"parent":null},{"elements":[],"url":"~/Member/ClubHomeSub/ClubPages.aspx","sequence":2,"linkText":"Club Pages","description":"Club Pages","uid":8,"parent":null}],"url":"~/Member/ClubHomeSub/ClubAdmin.aspx","sequence":1,"linkText":"Club Admin","description":"Club Admin","uid":4,"parent":null}],"url":"~/Member/ClubHome.aspx","sequence":3,"linkText":"Club Home","description":"Club Home","uid":3,"parent":null},{"elements":[],"url":"~/Member/GameAnalysis.aspx","sequence":4,"linkText":"Game Analysis","description":"Game Analysis","uid":6,"parent":null},{"elements":[],"url":"~/Member/SkillAquisition.aspx","sequence":5,"linkText":"Skill Aquisition","description":"Learn new game skills","uid":7,"parent":null}]"
Turns out you don't need to use a serializer at all.
You just return type object.
public object NavigationItems()
{
using (TTConnection connection = new TTConnection("ClientDb"))
{
if (MySession.Current.MyClub == null)
return USER_ERROR;
MiddleTier.WebNavigation.WebNavigationGenerator gen = MySession.Current.NavGenerator;
List<NavigationElement> list = gen.GetNavigation();
return list;
}
}