My wcf project returns the Countries List as json, in wcf project parse using Newtonsoft json. I get json in my client website built on mvc, i show the data using jtable plugin in jquery. The plugin failed to display because, the json contains /(back slashes).
Code to display jtable is
Name:{
title: 'Country Name',
width: '40%',
options: '/Country/Index'
}
Country/Index result is
{"Result":"OK","Options":"[{\"DisplayText\":\"India\",\"Value\":1},{\"DisplayText\":\"Singapore\",\"Value\":2}]"}
Country/Index gets the result from wcf service. Is there any way to strip the / in json.
Edit:
My wcf code is
List<JSONDisplayNameValue> lstLanguages = new List<JSONDisplayNameValue>();
//Get data from db.
//JSONDisplayNameValue has two variables DisplayName, Value
var json = JsonConvert.SerializeObject(lstLanguages);
return json;
Country/Index mvc code is
public JsonResult Index()
{
string Countries_list = processsvc.GetAllCountries();
return Json(new { Result = "OK", Options = Countries_list }, JsonRequestBehavior.AllowGet);
}
You are getting backslashes because you are double-serializing your data.
In your WCF code, you call JsonConvert.SerializeObject() to serialize your list of countries/languages to JSON before returning it.
In your MVC controller, you call your WCF service to get the list, which is already in JSON format. But then you add that JSON to another object and call Json() which causes the list to be serialized a second time. That is where the backslashes get added.
To fix this, you either need to
Deserialize the list you get back from your WCF service before adding it to the MVC result.
-- OR --
Make a way to retrieve your list of countries/languages without serializing it to JSON. Then add the unserialized list to your MVC result and serialize it as normal.
Related
I am working on ASP.NET MVC 4.0 application.
I am sending my form's value to controller like this in Kendo Window refresh option :-
var frm = $("#formUpdate");
var productWindow = $("#ProductWindow").data("kendoWindow");
productWindow .refresh({
url: "../../Product/UpdateProduct",
data: { model: JSON.stringify(frm.serializeArray())}
});
And below is the string that i am getting on controller :-
[{"name":"DefaultAddressNumber","value":""},{"name":"Id2","value":"tax id 1"}, {"name":"Id2","value":"tax id 2"},{"name":"Id","value":"5"},{"name":"ProductTaxes","value":""},{"name":"ProdcutId","value":"20"},{"name":"InsuranceId","value":""},{"name":"OrgAddr1","value":""},{"name":"OrgAddr2","value":""},{"name":"OrgAddr3","value":""},{"name":"Name","value":"Amit Kumar"},{"name":"Description","value":"Description"},{"name":"SelectedProductSubTypeId","value":""},{"name":"IsEmailFinalizedProduct","value":"False"}]
And i want to do deserialize that string again into form of array or object or something in which i can read/get it easily.
And for that i have used below code :-
var productString = Newtonsoft.Json.JsonConvert.DeserializeObject<ProductViewModel>(str);
But i am getting the below error while i am using this :
Cannot deserialize the current JSON array (e.g. [1,2,3]) into type
'ProductRepository.ViewModel.ProductViewModel' because the type
requires a JSON object (e.g. {"name":"value"}) to deserialize
correctly.
To fix this error either change the JSON to a JSON object (e.g.
{"name":"value"}) or change the deserialized type to an array or a
type that implements a collection interface (e.g. ICollection, IList)
like List that can be deserialized from a JSON array.
JsonArrayAttribute can also be added to the type to force it to
deserialize from a JSON array.
Path '', line 1, position 1.
Can any one help me out on this,means how can i parse this string ?
use JSON.stringify to outer side like..
var frm = $("#formUpdate");
var productWindow = $("#ProductWindow").data("kendoWindow");
productWindow .refresh({
url: "../../Product/UpdateProduct",
data: JSON.stringify({ model: frm.serializeArray()})
});
I'd like to use iqueryable on all my collections so that I get all of the odata features. However I need to format the response of the request with the following fields;
{
href: "url to resouce",
length: 10,
items: [
"(IQueryable results)"
]
}
Formatting the response isnt the hard part but keeping all of the odata "stuff" working is.
So my code looks like;
MyFormattedResponse.Href = "poop.com";
MyFormattedResponse.Length = 0;
MyFormattedResponse.Items = _myRepo.Gets();
Request.CreateResponse(HttpStatusCode.OK, MyFormattedResponse);
But the error I get is:
The action 'Get' on controller 'MyResource' with return type
'MyObject' cannot support querying. Ensure the type of the returned
content is IEnumerable, IQueryable, or a generic form of either
interface.
Is this something I can construct in a media formatter or perhaps a filter?
I really want to keep the odata awesomeness...
Take a look at this answer I've provided:
Web API Queryable - how to apply AutoMapper?
Your case is similar, you can do something like this:
public MyFormattedResponse Get(ODataQueryOptions<Person> query)
{
var results = query.ApplyTo(_myRepo.Gets()) as IEnumerable<Person>;
return new MyFormattedResponse() { Href = "foo.com", Length = 5, Items = results };
}
Make sure you remove the [Queryable] attribute.
Is it possible to deserialize a JSON string to an object without using the DataContractJsonSerializer in System.ServiceModel.Web? I have the following code but I need a payed license to use it...
response = (HttpWebResponse)request.EndGetResponse(iar);
System.Runtime.Serialization.Json.DataContractJsonSerializer ser = new System.Runtime.Serialization.Json.DataContractJsonSerializer(typeof(Result));
Result result = (Result)ser.ReadObject(response.GetResponseStream());
I'm using RestSharp to consume my Web.API service that sends data via JSON. However, I'm using JSON.NET to deserialize it.
_client.ExecuteAsync (request, (response) => {
List<Account> data = JsonConvert.DeserializeObject<List<Account>>(response.Content);
This works just fine for me and JSON.NET is free, very quick, and kind of the de facto JSON serialization library for .NET.
http://james.newtonking.com/projects/json-net.aspx
I'm learning aspnet mvc 4 web api, and find it very easy to implement by simply returning the object in the apicontrollers.
However, when I try to return value types such as bool, int, string - it does not return in JSON format at all. (in Fiddler it showed 'true/false' result in raw and webview but no content in JSON at all.
Anyone can help me on this?
Thanks.
Some sample code for the TestApiController:
public bool IsAuthenticated(string username)
{
return false;
}
Some sample code for the jQuery usage:
function isAuthenticated(string username){
$.getJSON(OEliteAPIs.ApiUrl + "/api/membership/isauthenticated?username="+username,
function (data) {
alert(data);
if (data)
return true;
else
return false;
});
}
NOTE: the jquery above returns nothing because EMPTY content was returned - however if you check it in fiddler you can actually see "false" being returned in the webview.
cheers.
Before your callback function is called, the return data is passed to the jquery parseJSON method, which expects the data to be in the JSON format. jQuery will ignore the response data and return null if the response is not formatted correctly. You have two options, wrap you return boolean in a class or anonymous type so that web api will return a JSON object:
return new { isAuthentication = result }
or don't use getJSON from jQuery since you're not returning a properly formatted JSON response. Maybe just use $.get instead.
Below is a quote for the jQuery documentation:
Important: As of jQuery 1.4, if the JSON file contains a syntax error,
the request will usually fail silently. Avoid frequent hand-editing of
JSON data for this reason. JSON is a data-interchange format with
syntax rules that are stricter than those of JavaScript's object
literal notation. For example, all strings represented in JSON,
whether they are properties or values, must be enclosed in
double-quotes. For details on the JSON format, see http://json.org/.
I Need by service contract to return the xml/json result depending on the request type.I also need a kind of helper function which will convert my result set (i am using linq to sql) so that i do not need to create the xml format for the result set by iterating through the table row many times.What is the suitable way to do that.
I need a kind of short cut method which will convert the table data to xml result.Had i been using asp.net mvc i would have been able to generate the xml data by overriding the the ExecuteResult method in the ActionResult and giving Conetnt-Type = "text/xml" as OP.But since i am using
Wcf i don't have the controller context(as controller context is the parameter that needs to be passed to Execute Result).
My present code for converting the table data to the xml format is below.
public XDocument UsersLists(string authToken)
{
bool IsAuthenticated = Authenticate(authToken);
XDocument xDoc = new XDocument();
XElement root = new XElement("Users");
if (IsAuthenticated)
{
List<User> lstUsers = _lService.UserRepository.GetUserCompanyFromAccountID(GetAccountId(authToken)).ToList();
if (lstUsers != null)
{
root.Add(new XElement("Message", "Success"));
foreach (var u in lstUsers)
{
XElement chid = new XElement("User");
root.Add(new XElement("UserId", u.UserId));
root.Add(new XElement("FirstName", u.FirstName));
root.Add(new XElement("LastName", u.LastName));
root.Add(new XElement("Email", u.Email));
root.Add(new XElement("CompanyName", u.Company.CompanyName));
root.Add(chid);
}
xDoc.Add(root);
return xDoc;
}
else
{
return ReturnFailure(xDoc, root);
}
}
else
{
return ReturnFailure(xDoc, root);
}
}
I need to eliminate this way of generating xml for each table records.
An early response is priceless.
Thanks
Technology : Windows Communication Foundation.
Implementation of single operation returning both XML or JSON differs between WCF 3.5 or WCF 4.0. For implementing this feature in WCF 3.5 check this thread. Generally you will have to create custom behavior and set the content type based on Accept header from the request. WCF 4.0 has native support for this feature. WebHttpBehavior has property AutomaticFormatSelectionEnabled. If you set this property to true it should just work out of the box.
To your second question. You don't need any custom formatting like in ASP.NET MVC. Formatting in WCF is handled by serialization. Just return collection from your operation and you will see what happens. Linq-To-Sql generated entities should be serializable by default. Just don't forget to execute query before returning from method. If you need special format of date which is not the same as Linq-To-Sql entities create custom data type which have public parameterless constructor and all required properties with getter and setter. If you want to make it clear makr that class with DataContract attribute and all properties with DataMember attribute. Return collection of that custom class instances from your operation.