Deserializing json data from jquery post method directly to string array - asp.net

Is there a way to deserialize an array sent by jquery post method to directly c# string array(string[])?
I tried posting data like this
$.post(url,
{
'selectedTeams[]'=['Team1','Team2']
},
function(response) {}, 'json');
And trying to consume it like this in C# class
string jsonData = new StreamReader(context.Request.InputStream).ReadToEnd();
var selectedTeams = new JavaScriptSerializer().Deserialize<string[]>(jsonData);
It didn't work and ofcource it should not as there is no property selectedTeams[] in string[]
I am aware of the way to define a class something like this
class Teams
{
public string[] SelectedTeams{get;set;}
}
and then do the deserialization.
But I think that is an unnecessary defining a class so isn't there a way to directly convert json array to c# string array
Thanks in advance.

Figure it out!
Using stringified array object rather than direct named json parameter to pass as data solved my problem
I am now posting like this
var Ids = new Array();
Ids.push("Team1");
Ids.push("Team2");
$.post(url, JSON.stringify(Ids), function(response) {}, 'json');
And now able to deserialize json response directly to string array like this
string jsonData = new StreamReader(context.Request.InputStream).ReadToEnd();
var selectedTeams = new JavaScriptSerializer().Deserialize<string[]>(jsonData);
Thanks!!

you could develop your own class, but I would suggest you use this:
http://json.codeplex.com/

Related

getting string like when I return a list

The result I am getting
falsef005fdc9-7781-4c75-9f54-0a05a7fc6e71bc3d0990-2f44-491f-a25a-3771772d6a61false2017-10-10T08:43:16.0831010019false
I am getting like the format as below when I use the postman.
Question: How do I remove []? I tried to remove ToList() but it didn't work.
Question: Why I am getting a string like result instead of json?
controller method
public IEnumerable<ClientModel> GetClients()
{
var clients = ClientHelper.GetAllClients();
var result = (from c in clients
select c).ToList();
return Mapper.Map<IEnumerable<ClientModel>>(result);
}
Use this namespace
using System.Web.Script.Serialization;
and
var json_result = new JavaScriptSerializer().Serialize(result );
You must get json data in json_result

How to return IEnumerable list of objects with WebApi?

I have an object called PostMapDB and a method which retrieves a list of those objects. I would like to be able to pass this list and retrieve the data using webapi.
The code bellow gets me an error:{"":["The input was not valid."]}
[HttpGet]
public string Get(PostMapDB list)
{
IEnumerable<PostMapDB> dataOfPosts = list.getAllPosts().OrderBy(x => x.Date);
var data = JsonConvert.SerializeObject(dataOfPosts, new JsonSerializerSettings()
{
ContractResolver = new DefaultContractResolver()
{
IgnoreSerializableAttribute = false
}
});
return data;
}
How does your request to server looks like?
What's the definition on PostMapDB?
Make sure you're passing data in a right way.
Probably the attribute FromBody would help:
public string Get([FromBody] PostMapDB list)
Reference: https://learn.microsoft.com/en-gb/aspnet/web-api/overview/formats-and-model-binding/parameter-binding-in-aspnet-web-api

Serialize JSON from dynamic ignoring a C# keyword

I'm using Json.net and all I need from it is the simplest form of creating a JSON string to send up as an HTTP POST. For that reason, I don't want to create a new custom object just to be able to serialize it correctly. So I chose the dynamic method in Json.net.
The JSON that I need looks something like this:
{
root: {
header: {
namespace: "",
name: ""
},
body: {
email: email
myArray:[
{
item1: "",
item2: ""
},
{
item3: "",
item4: ""
},
]
}
}
}
So I tried to do the following:
dynamic httpRequestBody = new JObject();
httpRequestBody.root = new JObject();
httpRequestBody.root.header = new JObject();
httpRequestBody.root.header.namespace = "";
httpRequestBody.root.header.name = "name;
But since "namespace" is a C# keyword, it doesn't let me use it. Is there a way to get around it since I need "namespace" as part of the JSON? If not, what's the simplest way of creating this JSON string?
To clarify, I don't have a very strong opinion against creating my own little class and serialize it, but it feels like since all i need is to send some jSON up and forget about it, I should be able to create it on the fly.
Rather than upcasting your JObject to be dynamic, keep it as an explicitly typed variable. JObject implements IDictionary<string, JToken> which can be used, along with the implicit conversion operators from primitive types to JToken, to set a property value of any name to any primitive value or other JToken:
var header = new JObject();
header["namespace"] = ""; // Here we use the implicit operator from string to JToken
header["name"] = "name";
httpRequestBody["root"]["header"] = header;
Using explicit typing also allows for compile-time checking of code correctness, and may improve performance.
Demo fiddle here.

Servicestack.net custom XML DateTime serialization

Is there a way to override the XML DateTime serialization in Servicestack.Net like we can do with JSON:
JsConfig<DateTime>.SerializeFn = date => new DateTime(date.Ticks, DateTimeKind.Local).ToString("dd.MM.yyyy HH:mm:ss");
I want to do the same thing for all XML DateTimes.
Edit:
I just found out I can hook into the XML serialization with this:
this.ContentTypeFilters.Register("application/xml", SerializeXmlToStream, DeserializeXmlFromStream);
public static void SerializeXmlToStream(IRequestContext requestContext, object response, Stream stream)
{
using (var sw = new StreamWriter(stream))
{
sw.Write(response.ToXml());
}
}
This returns the same XML as without this hook. If someone has any idea how I can change the serialiazation of DateTime to a custom format with this or any other global way please let me know.

ASP.NET WebMethod Returns JSON wrapped in quotes

I have an asp.net page with a WebMethod on it to pass JSON back to my javascript.
Bellow is the web method:
[WebMethod]
public static string getData(Dictionary<string, string> d) {
string response = "{ \"firstname\": \"John\", \"lastname\": \"Smith\" }";
return response;
}
When this is returned to the client it is formatted as follows:
{ \"d\": \"{ \"firstname\": \"John\", \"lastname\": \"Smith\" }\" }
The problem is the double quotes wrapping everything under 'd'. Is there something I've missed in the web method or some other means of returning the data without the quotes? I don't really want to be stripping it out on the client everytime. Also I've seen other articles where this doesn't happen.
Any help would be appreciated thanks.
I assume that you want to return the JSON representation of the object
{
firstname:"John",
lastname:"Smith"
}
but your method signature is returning a string. The ASP.Net framework serialisation is correctly serialising the string response. Put another way, if your function was
string response = "foo";
return response;
You would not be surprised if the output was
{"d":{"foo"}}
It just happens that response has double quotes that need to be escaped.
You obviously just want to get at the object. You have 2 options: -
1) use eval in your javascript to turn the string into an object e.g.
function onSuccessCallback(retval) {
var obj = eval(retval.d);
}`
2) or (and this is my prefered solution) have your method return an actual object and let the JSON serialisationof the framework do the heavy lifting for you
[WebMethod]
public static object getData(Dictionary<string, string> d) {
var response = new { firstname = "John", lastname="Smith" };
return response;
}
You will see that this generates the response that you probably originally expected (e.g.
{"d":{"firstname":"John", "lastname":"Smith"}}
Actually this entire issue exists because you're trying to out-think ASP.Net web services. You need to setup a class for your data to be returned and use that class (or List(of YourClass)) to queue up results and return them.
A great article explaining all this (a very common pitfall) is: http://encosia.com/asp-net-web-services-mistake-manual-json-serialization/
I had a similar issue with my code. I was trying to return an XmlDocument as JSON to a calling script but returning XmlDocument from the WebService returned an empty set of arrays (as XmlDocument is NOT serializable!).
If i set the ScriptService with the attribute ResponseFormat.JSON then my JSON was double-escaped.
The way to out-fox ASP.NET is to tell ASP.NET that you're returning XML and then it won't double-escape your JSON ;-)
[WebMethod(EnableSession = true)]
[ScriptMethod(ResponseFormat = ResponseFormat.Xml)]
public String MyJSONWebService(String sParam1, String sParam2, String sParam3)
{
... do stuff.....
XmlDocument oXMLDocument = new XmlDocument();
oXMLDocument.LoadXml(sXML);
sJSON = JsonConvert.SerializeXmlNode(oXMLDocument.SelectSingleNode("autnresponse"));
return sJSON;
}
I know it's a hack but .....

Resources