I have a POST method in my Web API controller that looks like this
public class StudentsController : ApiController {
public HttpResponseMessage Post(ApiStudent apiModel) {
// does processing here
}
}
public class ApiStudent {
public long Id { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public int GraduationClass { get; set; }
// other fields omitted for brevity
}
In cilent 1, I'm adding an ApiStudent directly to the body of the REST client, which results in JSON that does not have escape characters. This correctly automatically deserializes on the server side, but with client 2, when I send over JSON content with escape characters, the ApiStudent deserialized as NULL.
// DESERIALIZES PROPERLY ON SERVER
public void Client1() {
var student = new ApiStudent();
student.Id = 0; // new student since it's a post
student.FirstName = "Homer";
student.LastName = "Simpson";
student.GraduationClass = 2014;
var jsonRequest = new RestRequest("http://www.mydomain.com/api/students", Method.POST);
jsonRequest.RequestFormat = DataFormat.Json;
jsonRequest.AddBody(student);
IRestResponse jsonResponse = client.Execute(jsonRequest);
return jsonResponse;
}
// DESERIALIZES AS NULL ON SERVER
public void Client2() {
var jsonContent = "{ \"FirstName\": \"Api\", \"LastName\": \"Test\", \"GraduationClass\": 2014, \"Id\": 0 }";
var jsonRequest = new RestRequest("http://www.mydomain.com/api/students", Method.POST);
jsonRequest.RequestFormat = DataFormat.Json;
jsonRequest.AddBody(jsonContent);
IRestResponse jsonResponse = client.Execute(jsonRequest);
return jsonResponse;
}
Using fidder, I can see that client 1 sends over the following:
{ "FirstName": "Api", "LastName": "Test", "GraduationClass": 2014, "Id": 0 }
I can see that client 2 sends over the following:
{ \"FirstName\": \"Api\", \"LastName\": \"Test\", \"GraduationClass\": 2014, \"Id\": 0 }
Is there a way to either strip out the escape characters, or have them parsed properly on the server side?
I found a workaround for this, and I hope it helps somebody.
// NOW DESERIALIZES PROPERLY ON THE SERVER
public void Client2() {
var jsonContent = "{ \"FirstName\": \"Api\", \"LastName\": \"Test\", \"GraduationClass\": 2014, \"Id\": 0 }";
var jsonRequest = new RestRequest("http://www.mydomain.com/api/students", Method.POST);
jsonRequest.AddParameter("text/json", jsonContent, ParameterType.RequestBody);
IRestResponse jsonResponse = client.Execute(jsonRequest);
return jsonResponse;
}
Related
How can I Post for example this information of below to this website "http://restapi.adequateshop.com/api/Tourist"
by C# code?
tourist_name: "dummy"
tourist_email: "test123#test.com"
tourist_location: "Paris"
static void Main(string[] args)
{
//create the constructor with post type and few data
string data = "tourist_name=Mike&tourist_email=miked123#gmail.com&tourist_location=Paris";
MyWebRequest myRequest = new MyWebRequest("http://restapi.adequateshop.com/api/Tourist", "POST", data);
//show the response string on the console screen.
string Response = myRequest.GetResponse();
}
You can put your data in a new class :
class RequestData
{
string tourist_name { get; set; }
string tourist_email { get; set; }
string tourist_location { get; set; }
}
Then you can serialize your object to JSON:
RequestData requestData = new RequestData();
requestData.tourist_name ="Mike";
requestData.tourist_email ="miked123#gmail.com";
requestData.tourist_location ="Paris";
string jsonData = JsonConvert.SerializeObject(requestData);
Then send your JSON to API
string URL="http://restapi.adequateshop.com/api/Tourist";
var jsonContent = new StringContent(jsonData,Encoding.UTF8,"application/json");
var result = client.PostAsync(URL,jsonContent).Result;
I hope this answers your question.
I'm begginer in JSON deserialize objects. I tried to use JSON.NET.
I have a hardware device which send me a JSON message like this.
{
"settings": [{
"slotid": 13,
"live": {
"values": [
{"id":1,"v":"3.5.0"},
{"id":2,"v":""},
{"id":3,"v":282827},
{"id":4,"v":127},
{"id":5,"v":127},
{"id":10,"v":7},
{"id":11,"v":1},
{"id":12,"v":22},
{"id":13,"v":1},
{"id":14,"v":1},
{"id":15,"v":0},
{"id":16,"v":2},
{"id":17,"v":0},
{"id":18,"v":0}
]
},
"presets": []
}]
}
I tried to do it exactly as in
https://www.newtonsoft.com/json/help/html/DeserializeDataSet.htm
but something goes wrong, I suppose that it depends of building of JSON answer format.
I used code like this:
public class Product
{
public string settings {get; set;}
public string values { get; set; }
//public string presets { get; set; }
public string slotid { get; set; }
}
private void Form1_Load(object sender, EventArgs e)
{
string URL = "http://10.0.0.201/api/json/controls/get?slotid=13";
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(URL);
request.ContentType = "application/json; charset=utf-8";
HttpWebResponse response = request.GetResponse() as HttpWebResponse;
using (Stream responseStream = response.GetResponseStream())
{
StreamReader reader = new StreamReader(responseStream, Encoding.UTF8);
string json = reader.ReadToEnd();
try
{
Product deserializedProduct = JsonConvert.DeserializeObject<Product>(json);
}
catch(Exception E)
{
}
}
}
In json variable I keep JSON message.
I suppose that I have to build custom datatable, but how?
Regards
Ps.
I forgot to say that I need to get only "id" and "v" from JSON from values.
We are using 3rd party api kraken.io to optimize our images.
The results of optimized image is posted in a Webhook.
In their api document it states: After the optimization is over Kraken will POST a message to the callback_url specified in your request in a JSON format application/json.
I am using ngrok to allow remote webhooks to send data to my development machine, using this article.
Results posted to the Callback URL:
HTTP/1.1 200 OK
{
"id": "18fede37617a787649c3f60b9f1f280d",
"success": true,
"file_name": "header.jpg",
"original_size": 324520,
"kraked_size": 165358,
"saved_bytes": 159162,
"kraked_url": "http://dl.kraken.io/18/fe/de/37617a787649c3f60b9f1f280d/header.jpg"
}
Class to Map
public class KrakenOptimizedResults
{
public string id { get; set; }
public bool success { get; set; }
public string file_name { get; set; }
public int original_size { get; set; }
public int kraked_size { get; set; }
public int saved_bytes { get; set; }
public string kraked_url { get; set; }
}
Action Method
[HttpPost]
public ActionResult OptimizedWebHook()
{
Request.InputStream.Position = 0;
string jsonString = new System.IO.StreamReader(Request.InputStream).ReadToEnd();
KrakenOptimizedResults obj = new JavaScriptSerializer().Deserialize<KrakenOptimizedResults>
(jsonString);
return Json(obj);
}
But When I debug the received jsonString in Html Visualizer it looks like key and value pairs instead of Json format.
Received Results not Json Formatted:
file_name=header.jpeg&original_size=118066&kraked_size=102459&saved_bytes=15607
I guess the received data content-type: is application/x-www-form-urlencoded.
Why i am receiving key and value pairs instead of Json format ? how can I deserialize Json data in asp.net mvc ?
Co-founder of https://kraken.io here.
There is a glaring omission in our documentation which I will fix today. To get JSON back, you need to set a "json": true flag in the request. Omitting that flag or setting "json": false will return URLEncoded. Example cURL request:
curl http://api.kraken.io/v1/upload -X POST --form data='{"auth":{"api_key":"YOUR_KEY", "api_secret":"YOUR_SECRET"}, "wait": true, "lossy": true, "callback_url": "http://requestb.in/wbhi63wb", "json": true}' --form upload=#test.jpg
Sorry for the inconvenience :-(
I was able to convert Query String Key and Value pairs to Json Format using this and this post ,there is some delay to convert form Dictionary to Json, so If there is better answers, then do post and advice, below is my solution.
Action Method
[HttpPost]
public ActionResult OptimizedWebHook()
{
Request.InputStream.Position = 0;
string data = new System.IO.StreamReader(Request.InputStream).ReadToEnd();
var dict = HttpUtility.ParseQueryString(data);
var json = new JavaScriptSerializer().Serialize(dict.AllKeys.ToDictionary(k => k, k =>
dict[k]));
KrakenOptimizedResults obj = new JavaScriptSerializer().Deserialize<KrakenOptimizedResults>
(json);
return Json(obj);
}
Recieving JSON formated optimized results from kraken API.
As mentioned by #karim79, To get JSON back, you need to set a "json": true flag in the request.
As Kraken .Net/C# SDK didn't have option to set "json": true, so i have to extend their base class.
Extended Base Class:
public class OptimizeRequestBaseExtended : OptimizeRequestBase,
IOptimizeUploadRequest, IRequest
{
public OptimizeRequestBaseExtended(Uri callbackUrl)
{
CallbackUrl = callbackUrl;
}
[JsonProperty("callback_url")]
public Uri CallbackUrl { get; set; }
[JsonProperty("json")]
public bool JsonFormat { get; set; }
}
Request Kraken API:
var callbackUrl = new Uri("http://localhost:0000/Home/OptimizedWebHook");
OptimizeRequestBaseExtended settings = new OptimizeRequestBaseExtended(callbackUrl);
settings.Lossy = true;
settings.JsonFormat = true;
var response = client.Optimize(image: image, filename: filename, optimizeRequest: settings);
Action Method
[HttpPost]
public ActionResult OptimizedWebHook()
{
Request.InputStream.Position = 0;
string jsonString = new System.IO.StreamReader(Request.InputStream).ReadToEnd();
KrakenOptimizedResults obj = JsonConvert.DeserializeObject<KrakenOptimizedResults>
(jsonString);
return Json(obj);
}
Step 1:
Create an aspx page. This page must be able to accept HTTP POST request.
Step 2:
Add this code to get HTTP POST data.File: default.aspx.cs
File: default.aspx.cs
var reader = new StreamReader(Request.InputStream);
var json = reader.ReadToEnd();
FileStream ostrm;
StreamWriter writer;
TextWriter oldOut = Console.Out;
ostrm = new FileStream(#"C:\logfile4webhook.txt", FileMode.Append, FileAccess.Write);
writer = new StreamWriter(ostrm);
Console.SetOut(writer);
Console.Write(DateTime.Now + " ");
Console.WriteLine(json.ToString() + " ");
Console.SetOut(oldOut);
writer.Close();
ostrm.Close();
Step 3:
Create webhook. This code can be linked to a button on click event.File:default.aspx.cs
AuthenticationDetails auth = new ApiKeyAuthenticationDetails("your api key");
string listID = "";
listID = "your list id";
List list = new List(auth, listID);
List<string> events = new List<string>();
events.Add("Update");
string postback = list.CreateWebhook(events, "URL", "json");
FileStream ostrm;
StreamWriter writer;
TextWriter oldOut = Console.Out;
ostrm = new FileStream(#"C:\logfile4webhook.txt", FileMode.Append, FileAccess.Write);
writer = new StreamWriter(ostrm);
Console.SetOut(writer);
Console.Write(DateTime.Now + " ");
Console.WriteLine(postback + " ");
Console.SetOut(oldOut);
writer.Close();
ostrm.Close();
Step 4:
Activate webhook. Copy that webhook id from the text file and past it to the code below.
File:default.aspx.cs
AuthenticationDetails auth = new ApiKeyAuthenticationDetails("your api key");
string listID = "";
listID = "your list id";
List list = new List(auth, listID);
list.ActivateWebhook("webhook id");
Step 5:
Test weebhook.File: default.aspx.cs
AuthenticationDetails auth = new ApiKeyAuthenticationDetails("your api key");
string listID = "";
listID = "your list id";
List list = new List(auth, listID);
string postback = list.TestWebhook("webhook id").ToString();
FileStream ostrm;
StreamWriter writer;
TextWriter oldOut = Console.Out;
ostrm = new FileStream(#"C:\logfile4webhook.txt", FileMode.Append, FileAccess.Write);
writer = new StreamWriter(ostrm);
Console.SetOut(writer);
Console.Write(DateTime.Now + " ");
Console.WriteLine(postback + " ");
Console.SetOut(oldOut);
writer.Close();
ostrm.Close();
Step 6:
Deserialize body of JSON object. We need to create class structure based on JSON data. I put sample json here and it created required classes
public class CustomField
{
public string Key { get; set; }
public string Value { get; set; }
}
public class Event
{
public List<CustomField> CustomFields { get; set; }
public string Date { get; set; }
public string EmailAddress { get; set; }
public string Name { get; set; }
public string SignupIPAddress { get; set; }
public string Type { get; set; }
}
public class RootObject
{
public List<Event> Events { get; set; }
public string ListID { get; set; }
}
Once you have created your class, append the code from step 2 after
var json = reader.ReadToEnd();
to deserialize and parse json.
RootObject myClass = JsonConvert.DeserializeObject(json);
if (myClass != null)
{
List<Event> t = myClass.Events;
string old_email = "", new_email = "";
old_email = t[0].OldEmailAddress;
new_email = t[0].EmailAddress;
//now you can do your logic with old_email and new_email
}
I have a question about inserting a json formatted string into a json structure and having the final version be a combined JSON formatted string that can be serialized into a JSON structure. I am using the newtonsofts Json.NET
I have the following JSON structure:
public class ResponseJson
{
[JsonProperty(PropertyName = "header")]
public ResponseHeader responseHeader { get; set; }
[JsonProperty(PropertyName = "results")]
public string responseResults { get; set; }
}
public class ResponseHeader
{
[JsonProperty(PropertyName = "name")]
public string name { get; set; }
[JsonProperty(PropertyName = "version")]
public string version { get; set; }
}
In the code, I do the following:
ResponseJson responseJson = new ResponseJson();
responseJson.responseHeader = new ResponseHeader()
{
name = A_NAME,
version = A_VERSION
};
responseJson.responseResults = resultJson;
return JsonConvert.SerializeObject(responseJson, new JsonSerializerSettings { NullValueHandling = NullValueHandling.Ignore });
resultJson is a properly formatted JSON string (in this case, an array of objects, but could be anything JSON formatted). Right now, if i execute the code, I get the following (which is expected, since "results" is declared as a string):
{
"header":
{
"name":"abcd",
"version":"1.0"
},
"results":
"[{\"data\":{\"level\":\"100\"},\"code\":{\"value\":\"JBC\",\"type\":\"ev\"},\"time\":{\"start\":\"20\",\"end\":\"101\"}}]"
}
what I do need as an output is:
{
"header":
{
"name":"abcd",
"version":"1.0"
},
"results":
[
{
"data":
{
"level":"100"
},
"code":
{
"value":"JBC",
"type":"ev"
},
"time":
{
"start":"20",
"end":"101"
}
}
]
}
While you don't explain how you create your resultJson variable, it's implied from your code that you are double-serializing your results: you compute an array of "result" classes, serialize them to a JSON string, store the string in your ResponseJson class, and them serialize that in turn. The embedded JSON string then gets escaped as per the JSON standard, which is what you are seeing.
You need to avoid double-serializing your data, for instance by using the following data model:
public class ResponseJson<T>
{
[JsonProperty(PropertyName = "header")]
public ResponseHeader responseHeader { get; set; }
[JsonProperty(PropertyName = "results")]
public T responseResults { get; set; }
}
public static class ResponseJson
{
public static ResponseJson<T> Create<T>(T responseResults, ResponseHeader responseHeader)
{
return new ResponseJson<T> { responseResults = responseResults, responseHeader = responseHeader };
}
}
public class ResponseHeader
{
[JsonProperty(PropertyName = "name")]
public string name { get; set; }
[JsonProperty(PropertyName = "version")]
public string version { get; set; }
}
Then you would do:
var results = GetResults(); // Get your result data
var responseJson = ResponseJson.Create(results, new ResponseHeader()
{
name = A_NAME,
version = A_VERSION
});
return JsonConvert.SerializeObject(responseJson, new JsonSerializerSettings { NullValueHandling = NullValueHandling.Ignore });
If for whatever reason you must embed a previously serialized JSON string as JSON rather than as a string literal, you'll need to re-parse it back to a JToken:
string resultJson = GetResultJson(); // Get result json string.
var responseJson = ResponseJson.Create(JToken.Parse(resultJson), new ResponseHeader()
{
name = A_NAME,
version = A_VERSION
});
return JsonConvert.SerializeObject(responseJson, new JsonSerializerSettings { NullValueHandling = NullValueHandling.Ignore });
Json.NET will include the JToken in your outer JSON as nested JSON rather than as a string literal.
How to send a file inside JSON to a service?
[OperationContract]
[WebInvoke(RequestFormat = WebMessageFormat.Json)]
public string Upload(UploadRequest request)
{
return request.FileBytes.Length.ToString();
//return request.FileName;
}
[DataContract]
public class UploadRequest
{
[DataMember]
public int ProfileID { get; set; }
[DataMember]
public string FileName { get; set; }
[DataMember]
public byte[] FileBytes { get; set; }
}
I tried FileBytes as Stream, but received and error: "cannot create instance of an abstract class".
$('#file2').change(function () {
var request =
{
"ProfileID": 1,
"FileName": this.files[0].name,
"FileBytes": this.files[0]
}
var xhr = new XMLHttpRequest();
xhr.open('POST', 'http://localhost:45039/Files.svc/Upload', true);
xhr.setRequestHeader("Content-type", "application/json");
xhr.onreadystatechange = function (aEvt) {
if (this.readyState == 4) {
if (this.status == 200)
$("#status").html(this.responseText);
else
$("#status").html("Error " + this.status.toString() + ": " + this.responseText);
}
};
xhr.send(JSON.stringify(request));
});
If the file is sent directly (xhr.send(this.files[0]) with Upload(Stream myfile), then WCF converts the posted file to a Stream. Is there a way to do that with the Stream inside the DataContract?
It turns out the answer is yes. You have to define the class as a MessageContract rather than a DataContract with only one property allowed to be a [MessageBodyMember]. The other properties to be [MessageHeader].
WCF will not map multi-part form data to a DataContract or MessageContract. Apparently this is due to WCF not buffering the message body and streaming it instead. The message body could be quite large so that does make sense.