.NET Tutorials, Forums, Interview Questions And Answers
Welcome :Guest
Sign In
Win Surprise Gifts!!!

Top 5 Contributors of the Month
Gaurav Pal
Post New Web Links

DataContract & json i dont know how to do this...

Posted By:      Posted Date: September 15, 2010    Points: 0   Category :ASP.Net
Hello,at work we are migrating all the application to .Net 4.0 and leaving behind the Newtonsoft json serializer with the Microsoft serializer.the thing is that in Newtonsoft you have a couple of attributes that apply to my needs.JsonObject(MemberSerialization.OptIn) <--- this makes that only serialize the properties that have the following attribute.JsonProperty("id")Is there a way of accomplish the same with datacontract or something???i dont want to make a custom converter, i have plenty of classes and make custom converters to all of them, its impossible...well... thanks for any info...greetings!!!

View Complete Post

More Related Resource Links

create user wizard login error message dont show in a message box?




i am using create user wizard and capturing other information within content template when a new user

registers. Some of the textboxes are binded to required field validators.


there is a validation control on the page and ShowMessage box is True.

If they dont complete some of the text boxes then the message box pops Up with the error message.

It does not however include information errors like "User already exists" or Email address already exists

from the create user wizard membership  UserName and Password Textboxes


is it possilbe to hook all of these up so I get one message box with all errors including membership ones?




WCF Data Service to JSON example? v4


I would like to take WCF Data Service and produce JSON output to consume on various mobile apps.

Can anyone give me a how-to on the JSON part?  I.e., what is different than normal XML outut?



Json Deserialization is giving error in IronPython



Have anyone tried json deserialization. When I tried:

>>> import json

>>> json.loads('["foo", {"bar":["baz", '"Test", 1.0, 2]}]')

I got following error:

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "C:\Program Files\IronPython 2.6 for .NET 4.0\Lib\json\__init__.py", line
 307, in loads
  File "C:\Program Files\IronPython 2.6 for .NET 4.0\Lib\json\scanner.py", line
42, in iterscan

simple json post url api



I am a json newbie :)

I have this site that has an api that can provide city name if I send my zip code as a parameter. 


the result is returned as a json object. Now i just want to read the result in my js function.

I have tried the following but it always returns null:

function postnr() {
    var url = 'http://www.postnummersok.se/api?q=16447';

Writing Data to database with jQuery Forms, ASMX Webservice, & JSON - help!



Can someone point me in the right direction on how to submit data from a jQuery form to a ASMX webservice? I have gotten everything on the form ready to be submitted to the database and now I am stuck on how to send it over using $.ajax(). Everything I have read tells me how to get data from a webservice and display it with jQuery, but not the other direction nor how to access the json data within the within the webservice service(similar to a Request.Form approach with ASP.NET forms).

In other words: 

1. What do I need to do to my webservice to make sure it can receive data from the jQuery form. 

2. What do I need to do in jQuery to receive an acknowledgement the save on the server side was successful. 

I can explain more if need be, but if there is a comprehensive tutorial on not only reading, but also WRITING data with jQuery, JSON, etc. I would love to get pointed in that direction. 

JSON Deserialize into Entity Framework Object and setting the DataMemberAttribute "Name="




I'm in the process of deserializing a JSON object into an Entity Framework object.  The property names in the JSON do not match up totally with the property names in the Entity Framework Objects. What I'd like to do is set "Name=" on the  "DataContractAttribute" for the table and the "DataMemberAttribute" for the properties in the Designer.cs file.  I tried setting these in the Designer.cs file manually just to see if it would work - which it did (using JSON.Net) but of course when I went into the .edmx designer I lost all my changes.  Is there a way to do this?


Thanks in advance

unable to use wcf service with json in asp.net



I have developed a wcf service for asp.net ajax client. It includes the following steps.

(1) Created WCF sevice contract with the operation "DoWork()" which will take string as input and retun string as output.

(2)Implemented the above operation contract(attributed the implementation class with aspnetcompatibility requirement as enabled).

(3)Added the webscriptenabled to endpoint in web.config file.

(4)Hosted the wcf servie. 

(5)Downloaded the javascript file from the service.(e.g.,http://localhost/service1.svc/js)


(1)Opend new asp.net webapplication.

(2)Added the downloaded .js file.

(3)Given the scripts path for ajaxscript manager as both .js file and service url.


<asp:ScriptManager ID="id1"

Customizing the Converter for Json.NET


Many recently days, I thought about Json.net library that implemented by James. It is really a good library that I have ever used. I really impressed about many Converters that this library expose for user. I can list some converter of json.net at here:

+ BinaryConverter
+ BsonObjectIdConverter
+ DataSetConverter
+ DataTableConverter
+ EntityKeyMemberConverter
+ HtmlColorConverter
+ IsoDateTimeConverter
+ JavaScriptDateTimeConverter
+ KeyValuePairConverter
+ RegexConverter
+ StringEnumConverter
+ XmlNodeConverter

As you see, json.net have many converters, but still not enough for our necessary. So in this post, I try to explorer about 2 converters that I thought it is very useful for us. That are ArrayConverter and Object Converter (it is named by me). In 2 converter, I mainly implement it for return the object's interface, so it can be re-use and extension better. Now this is my code for implement it:
+ CustomObjectCreationConverter

    internal class 

make json call to send an email


the aspx:

<div class="contactSubmit">
                <asp:ImageButton ID="ibSubmit" runat="server" ValidationGroup="vgContact" /></div>


the jquery :

$(document).ready(function () {
            // Add the page method call as an onclick handler for the div.
            $(".contactSubmit").click(function () {
                    type: "POST",
                    url: "Home.aspx/GetDate",
                    data: "{}",
                    contentType: "application/json; charset=utf-8",
                    dataType: "json",
                    success: function (msg) {
                        // Replace the div's content with the page method's return.

The problem is that I need to use the text in a text box in my webmethod, and I can't because it's static, this results in a compilation error:

    public static string SendContactForm()


Deserialize JSON object in C#

Hi, I am new to JSON and one of my service is returning JSON object as a string to my application. I need to Deserialize JSON object in C#. My JSON string is in the current format. string str = "{\"candidates\":[{\"address\":\"1580 MARKET ST, SAN FRANCISCO, CA, 94102\",\"location\":{\"x\":-122.42054,\"y\":37.7745960000001},\"score\":40,\"attributes\":{}},{\"address\":\"1576 MARKET ST, SAN FRANCISCO, CA, 94102\",\"location\":{\"x\":-122.420355,\"y\":37.7747030000001},\"score\":40,\"attributes\":{}}]}"; Can anyone please help me how to get all the address, locations, score and attributes from the above string. Thankyou, Ravi.

two adjacent double quotes in json causes blue screen by JavaScriptSerializer

Hello, I am using System.Web.Script.Serialization.JavaScriptSerializer to deserialize  http requests.  I get the blue screen when the contents I am deserializing has two double quotes, for example:  ""country"". Is there a fix for this?  Currently I replace the "" with a special string and then I deserialization, then I put back the "".  I do this for a given field in the object which I've seen comes in with ""s.  The problem is that I should be doing this for all fields in the input json.  This is a lot of extra code to write as I could be deserializing many different types of Json objects.  The "" is needed by the client to specify a quoted string, so I can't ask for the input to be changed. Any help on this subject would be really appreciated. Many thanks.     I am using .Net framework 3.5.

SerializationException using JSON Serializer

I'm getting a SerializationException with the following message when I deserialize a simple object serialized with JSON: Expecting element 'root' from namespace ''.. Encountered 'None'  with name '', namespace ''. Any ideas what's wrong?  Here is the code: namespace     JSONSerialization {     class Program { [   DataContract ]     public class Info { [   DataMember ]     public string version; }     static void Main( string [] args) {     Info apiInfo = new Info () {version = "1.0" };     MemoryStream stream1 = new MemoryStream ();     DataContractJsonSerializer ser = new DataContractJsonSerializer ( typeof ( Info )); ser.WriteObject(stream1, apiInfo   );     Info proxyReceived = ( Info )ser.ReadObject(stream1);     Console .WriteLine( string .Format( "{0}: {1}" , "API version" , proxyReceived.version)); } } }

jQuery UI Autocomplete, Web Services and JSON

Hi guys, this is my first post, I´m desperate after wasting 2 days in google and reading forums ans sites. I can´t make it work. I just want to provide the name of cities to show in the autocomplete plugin. Let´s go part by part:WEB SERVICE: I use the Json.Net component to serialize a datasetpublic string ConsultTable(string data) { SqlConnection connection = new SqlConnection(WebConfigurationManager.ConnectionStrings["SqlServerConnection"].ToString()); SqlCommand command = new SqlCommand("SELECT name FROM cities",connection); connection.Open(); DataSet dataset = ToDataSet(command.ExecuteReader()); Newtonsoft.Json.JsonSerializer json = new Newtonsoft.Json.JsonSerializer(); json.NullValueHandling = NullValueHandling.Ignore; json.ObjectCreationHandling = Newtonsoft.Json.ObjectCreationHandling.Replace; json.MissingMemberHandling = Newtonsoft.Json.MissingMemberHandling.Ignore; json.ReferenceLoopHandling = ReferenceLoopHandling.Ignore; json.Converters.Add(new DataSetConverter()); StringWriter sw = new StringWriter(); Newtonsoft.Json.JsonTextWriter writer = new JsonTextWriter(sw); writer.Formatting = Formatting.None; writer.QuoteChar = '"'; json.Se

How to make my WCF client send JSON?

Hi, I have a WCF Service that accepts and sends JSON objects, defined like the following: [OperationContract] [WebInvoke(Method = "POST", UriTemplate = "/booking/", RequestFormat = WebMessageFormat.Json, ResponseFormat = WebMessageFormat.Json, BodyStyle = WebMessageBodyStyle.Wrapped)] Int32 booking(order o); now I have used SvcUtil.exe to create a client class and using that, I am trying to access my service - but even though I use "webHttpBinding" with "webHttp" behavior, it always sends it's messages in xml. What do I have to do make my client speak JSON?  

Routing pox, json & soap

I have a service exposed as pox, json & soap, as described at http://www.codemeit.com/wcf/wcf-restful-pox-json-and-soap-coexist.html. It exposes the endpoints: - http://localhost:81/TestService/soap - http://localhost:81/TestService/pox - http://localhost:81/TestService/json I now want to have a router, and to verify functionality, just expose it at http://localhost:82/... and have it forward calls to http://localhost:81/... I get this to work fine with the pox endpoint by following the initial steps at http://msdn.microsoft.com/en-us/magazine/cc500646.aspx, but I can't get it to work with soap or json. How should this be set up to have one router handle calls to all three enpoints? Hälsningar Anders

Is it a good practice to use DataContract attributes on business entities

Hi Folks, Currently I am developing a framwork for travel industry and finally my framework will expose its operations in the form of WCF Service. I was wondering if it is a good idea to decorate your entities and class with DataContract attributes. I know this is required if you want your classes/fields to be serialized/deseralized.  However, by Adding these attributes mean you are making your entities service specific which I believe not a good idea. Service and domain specific entities should be seperate. One solution to this would be to make DTOs and decorate them with these attributes and this make sense as core purpose of these DTOs is serialization and deserialization. What can be other options....? Please share your thoughts. Thanks, Naeem

IE 8 partially cut of my JSON data return from WCF service

Hi All, I am not so sure here is the right place to post my issue. I am using ExtJS treepanel and ajax call to wcf webservice and return JSON array. My service return array. If array count is less than 2, then IE partially cut of my JSON data return from WCF service. But FireFox is working fine with same JSON format string. Very interesting thing is that I try to debug with Fildder. so I have to put "." dot in my url "http://localhost{.}:1234/ then It is working fine.   I am testing with IE8. Here is the JSON format return from FF and FireBug. {"result":[{"href":"..\/EMP\/EmployeeSearch.aspx","iconCls":"","id":"8c362443-7bb3-427e-910c-87b391c6abf5","leaf":true,"text":"Employees"}]} Here is the corrupted JSON string retrun from IE using developer tool. {"result":[{"href":"..\/EMP\/E" [OperationContract] [WebInvoke(Method = "POST", UriTemplate = "GetSiteMap", BodyStyle = WebMessageBodyStyle.Wrapped, RequestFormat = WebMessageFormat.Json, ResponseFormat = WebMessageFormat.Json)] [return: MessageParameter(Name = "result")] List<TreeView> GetSiteMap(string node);
ASP.NetWindows Application  .NET Framework  C#  VB.Net  ADO.Net  
Sql Server  SharePoint  Silverlight  Others  All   

Hall of Fame    Twitter   Terms of Service    Privacy Policy    Contact Us    Archives   Tell A Friend