Thanks Mythz for providing such an amazing and powerful framework. However, I encountered the DateTime property rendered like this "/Date(1543681261000-0000)/" instead of "2019-03-25T12:50:3000" by using servicestack autoquery. I couldn't find any relevant docs. Please help me.
{
"customer": [
{
"transaction_total": 0,
"text": "0067 83228780",
"transaction_time": 0,
"action": 0,
"point_collection_on_registration": false,
"id": 71,
"push_notification_id": "null",
"name": "0067",
"ic": "27668",
"type": 0,
"phone_no": "83228780",
"point": 5132,
"balance": 1621.3,
"issue_date": "/Date(1543681261000-0000)/",
"is_subscribed": true,
"is_expiry": false,
"lang_preferred": "cn",
"is_delete": false
}
],
"count_all": 120
}
ServiceStack by default uses WCF Dates for JSON, see this answer for different ways to parse WCF Dates in JavaScript.
You can choose to change how dates are serialized in JSON for any JSON Response in ServiceStack by customizing JSON Responses, e.g you can change the JSON returned by the Auto Query Service with:
?jsconfig=DateHandler:ISO8601
?jsconfig=DateHandler:ISO8601DateOnly
?jsconfig=DateHandler:ISO8601DateTime
Or use the short-hand alias notation:
?jsconfig=dh:iso8601
?jsconfig=dh:iso8601do
?jsconfig=dh:iso8601dt
Alternatively you can tell ServiceStack to always use ISO8601 dates in JSON in your AppHost.Configure() with:
JsConfig.Init(new Config {
DateHandler = DateHandler.ISO8601
});
Related
I have a TimeSpan property
public TimeSpan Time { get; set; }
Currently using swagger to test API
Trying to figure out what value value to pass here
"time": {},
Tried:
"time": {"01:01:01"},
"time": {"01:01"},
"time": "01:01:01",
"time": 01:01:01,
all returning 401 code
On this another page you will find the solution to the problem: .Net Core 3.0 TimeSpan deserialization error - Fixed in .Net 5.0.
In a complementary way, add this in the swagger
c.MapType<TimeSpan>(() => new OpenApiSchema
{
Type = "string",
Example = new OpenApiString("00:00:00")
});
I write an ASP.NET Core REST API. The end point return the JSON.
The API parse JSON schema red from a file.
The JSON Schema has some value as arrow function as given below.
The Newtonsoft unable parse the JSON Schema without quotes in arrow function in validation message as below.
"ip": {
"$id": "#/properties/ip",
"type": "string",
"title": "The Ip Schema",
"default": "",
"examples": [
"111.123.789.654"
],
"pattern": "^(\\d{1,3}\\.){3}\\d{1,3}$",
"widget": {
"formlyConfig": {
"validation": {
"messages": {
"pattern": (error, field: FormlyFieldConfig) => `${ field.formControl.value } is not a valid IP Address`
}
}
}
}
}
The following C# code fail, since JSON is not valid.
var wraperobject = JObject.Parse(ui_schema);
If I add quotes like below as given below, the parsing works. I need to send it to UI without quotes, otherwise all consumer need to do manipulation at client side.
Please give me a solution.
"ip": {
"$id": "#/properties/ip",
"type": "string",
"title": "The Ip Schema",
"default": "",
"examples": [
"111.123.789.654"
],
"pattern": "^(\\d{1,3}\\.){3}\\d{1,3}$",
"widget": {
"formlyConfig": {
"validation": {
"messages": {
"pattern": "(error, field: FormlyFieldConfig) => `${ field.formControl.value } is not a valid IP Address`"
}
}
}
}
}
JSON should be able to have value as arrow function with quotes enclosed.
I can send it as string but need to escape the entire JSON to make it as a string. The UI side JSON parsing to be done.
Please let me know if there best alternative.
The value of a JSON property can be one of: object, array, string, number, "true", "false", or "null".
The value of "pattern" is none of those
"pattern": (error, field: FormlyFieldConfig) => `${ field.formControl.value } is not a valid IP Address`
Since that value isn't valid for JSON, JSON.Net (or any other parser) cannot interpret it.
When you quote your value, it becomes a valid string, which is why the parser can handle it.
I currently have this WEB API running locally:
// POST api/CsvParse
[HttpPut]
public void Put([FromBody]string value)
{
if (string.IsNullOrEmpty(value))
throw new Exception("Input is null or empty.");
}
I currently have it running locally, and am sending a string to the put using POSTMAN. I have selected the body tab, and have the string pasted into the raw body tab:
It states that my text is unsupported, or when I add a break point the value is null or I get the error describing the format is incorrect.
What am I doing wrong?
That's because there is no media type formatter that can serialize a raw string into your model (your route parameter with [FromBody] attribute).
A quick and dirty workaround is to directly read the body of your request as a string:
[HttpPut]
public async Task<HttpResponseMessage> Put(HttpRequestMessage request)
{
var myCsv = await request.Content.ReadAsStringAsync();
// do stuff with your string
return new HttpResponseMessage(HttpStatusCode.OK);
}
As an alternative you could implement a custom media type formatter yourself, as per this answer.
Change the media type to x-www-form-urlencoded rather than multipart/form-data.
Also, WebAPI is particular about FromBody parameters.
http://encosia.com/using-jquery-to-post-frombody-parameters-to-web-api/
For you, I think this is the relevant part:
[FromBody] parameters must be encoded as =value
The final hurdle remaining is that Web API requires you to pass
[FromBody] parameters in a particular format. That’s the reason why
our value parameter was null in the previous example even after we
decorated the method’s parameter with [FromBody].
Instead of the fairly standard key=value encoding that most client-
and server-side frameworks expect, Web API’s model binder expects to
find the [FromBody] values in the POST body without a key name at all.
In other words, instead of key=value, it’s looking for =value.
This part is, by far, the most confusing part of sending primitive
types into a Web API POST method. Not too bad once you understand it,
but terribly unintuitive and not discoverable.
Try adding a content type of text/plain
There is a similar Q&A here
I found that solution #1 worked for me as I was trying to PUT JSON containing the Key/Value pair. So originally my JSON looked like this
{
"subscriber": {
"Id": "2",
"subscriptions":[
{
"Name": "Subscription 1",
"Id": "18",
"IsSubscribed": false
},
{
"Name": "Subscription 2",
"Id": "19",
"IsSubscribed": false
},
{
"Name": "Subscription 3",
"Id": "20",
"IsSubscribed": false
}
]
}
}
But I modified it to become
{
"Id": "2",
"subscriptions":[
{
"Name": "Subscription 1",
"Id": "18",
"IsSubscribed": false
},
{
"Name": "Subscription 2",
"Id": "19",
"IsSubscribed": false
},
{
"Name": "Subscription 3",
"Id": "20",
"IsSubscribed": false
}
]
}
And that worked. My PUT request from Postman was recognised in my C# web api using [FromBody]
Just to add my bit, there is one more solution to pass primitives into a POST or a PUT method. Just specify the model as JObject. ASP.Net core web api then binds incoming JSON object(containing primitives like string) into JObject model object.
Your code would look like this:
// POST api/CsvParse
[HttpPut]
public void Put([FromBody]JObject value)
{
//access your string data
string data = value[SPECIFY_KEY_HERE];
if (string.IsNullOrEmpty(data))
throw new Exception("Input is null or empty.");
}
I am new to C#, and did not find an easy piece of code to read a response from a URL. Example:
http://www.somesitehere.com/mysearch
The response is something like this ( I do not know what kind of response is this):
{ "response": {
"status": {
"code": "0",
"message": "Success",
"version": "4.2"
},
"start": 0,
"total": 121,
"images": [
{
"url": "www.someimagelinkhere.com/pic.jpg",
"license": {
"url": "",
"attribution": "",
"type": "unknown"
}
}
]
}}
After that I will to save that url "www.someimagelinkhere.com/pic.jpg" to a file. But this I know how to do. I just want to separate the url from the rest.
I saw this topic: Easiest way to read from a URL into a string in .NET
bye
Your response is of JSON Format. Use a library (NewtonSoft but there are others too) to extract the node you want.
You can use something like JSON.NET by Newton soft, which can be found and installed using NuGet Package Manager in Visual Studio.
Also you could just do this.
var jSerializer = new JavaScriptSerializer();
var result = jSerializer.DeserializeObject("YOUR JSON RESPONSE STRING");
The JSON string will not be a C# object with properties that match your names such as start, total, images, etc. If you need to you can create a strong type object and cast your converted object to that one for ease of use.
Strong typed version:
var jSerializer = new JavaScriptSerializer();
var result = (YourStrongType)jSerializer.DeserializeObject("YOUR JSON RESPONSE STRING");
var imgUrl = result.images[0].url;
Using C# and Visual Studio 2010 (Windows Form Project), InstaSharp and Newtonsoft.Json libraries.
I want to get the image url from the JSON string returned to me by the Endpoint Instagram API when I request for a particular hashtag.
I can so far retrive the JSON string.
I am trying to use Newtonsoft.Json to deserialize the object using the examples, but I probably dont understand the JSON string representation of the object properly.
Below is a simplified sample response I get from the api call tags/tag-name/media/recent from their documentation. source here
{
"data": [{
"type": "image",
"filter": "Earlybird",
"tags": ["snow"],
"comments": {
}
"caption": {
},
"likes": {
},
"created_time": "1296703536",
"images": {
"low_resolution": {
"url": "http://distillery.s3.amazonaws.com/media/2011/02/02/f9443f3443484c40b4792fa7c76214d5_6.jpg",
"width": 306,
"height": 306
},
"thumbnail": {
"url": "http://distillery.s3.amazonaws.com/media/2011/02/02/f9443f3443484c40b4792fa7c76214d5_5.jpg",
"width": 150,
"height": 150
},
"standard_resolution": {
"url": "http://distillery.s3.amazonaws.com/media/2011/02/02/f9443f3443484c40b4792fa7c76214d5_7.jpg",
"width": 612,
"height": 612
}
},
"id": "22699663",
"location": null
},
...
]
}
I want to get specifically the standard_resolution in the images part.
This is the revelevant code that I currently have.
//Create the Client Configuration object using Instasharp
var config = new InstaSharp.Endpoints.Tags.Unauthenticated(config);
//Get the recent pictures of a particular hashtag (tagName)
var pictures = config.Recent(tagName);
//Deserialize the object to get the "images" part
var pictureResultObject = JsonConvert.DeserializeObject<dynamic>(pictureResult.Json);
consoleTextBox.Text = pictureResult.Json;
var imageUrl = pictureResultObject.Data.Images;
Console.WriteLine(imageUrl);
I get the error: Additional information: Cannot perform runtime binding on a null reference
so imageUrl is indeed null when I debug, hence indicating I am not accessing it the right way.
Anyone can explain to me how to access different parts of this JSON String using Newtonsoft.Json?
Using Newtonsoft.Json
dynamic dyn = JsonConvert.DeserializeObject(json);
foreach (var data in dyn.data)
{
Console.WriteLine("{0} - {1}",
data.filter,
data.images.standard_resolution.url);
}
I wrote a plugin for .net which takes care of deserializing the json string and returning a data table. it is still in development but see if it helps. Instagram.NET on Github