Rectangle 27 3

It seems to me that your main problem that you try to manually use JavaScriptSerializer().Serialize instead of returning an object. The response from the web service will be double JSON encoded.

UPDATED: Sorry, but you have a small error somewhere what you didn't posted. To close the problem I created a small project with an old version of Visual Studio (VS2008) which has practically exactly your code and which work. I placed it on http://www.ok-soft-gmbh.com/jQuery/WSMember.zip. You can download it, compile and verify that it works. Then you can compare your code with my and find your error.

Oleg, On a slightly different topic, is changing these services to WCF REST strongly advised?? You seem to be all for it here...! stackoverflow.com/questions/3189653/

People downvote me for saying it, but I don't recommend using WCF for simple AJAX callbacks. WCF is far more powerful, but doesn't really bring much to the table if you aren't using that power. In fact, ASMX's JavaScriptSerializer is actually more flexible than WCF's DataContractJsonSerializer when it comes to dates and enums. WCF's added complexity is hard to justify in this scenario (they're working on it though).

Oleg, your example drew my attention to one single line of code which fixed it. Thank you very much. The code was actually OK. for the button you have type="button". I had type="submit". I had just taken an old form and edited it... without noticing the type for the button. Also, I updated my jquery reference to 1.4.2 (I was still referring to 1.3.2) just for the sake of upating. I also use your "stringify" suggestion, although $.toJSON(myData) works too. Dave -- many thanks for your comments too. Very helpful.

@Dave: I agree with you, that different technique are introduced for the special case where they do exactly what needed. I used mostly WCF, but agree that JavaScriptSerializer has some nice features which I also miss in DataContractJsonSerializer. In all cases if somebody ask something about ASMX in his question and his problem is easy enough, than I didn't recommend him to switch to WCF. Both technique are good enough in the most cases.

asp.net - Returning JSON from ASMX, and handling it correctly in Javas...

asp.net jquery ajax json asmx
Rectangle 27 10

DataContractJsonSerializer
ResponseFormat = ResponseFormat.Json
public SimpleMessage SayHelloObject()

Moreover if you have {"Message":"Hello World"} in a string and display it in debugger it will be display as "{\"Message\":\"Hello World\"}", so exactly like you see string json = JsonConvert.Serialize(message); (Json.Net). So it seems to me that you have in both cases the same results.

To verify this use a client software which read the results. See some examples

UPDATED: In your code you define method SayHelloString(). It's result are a string. If you call the method this string will be one more time JSON serialized. JSON serialization of the string {"Message":"Hello World"} is a quoted string (see http://www.json.org/ definition for not a object, but a string) or exactly string "{\"Message\":\"Hello World\"}". So everything is correct with both methods of your Web Service.

UPDATED 2: I am glad that my tip from "Update" part of my answer helped you to swich of the double JSON serialization.

Nevertheless I would recommend you to change a little the solution to stay more at the WCF concept.

If you want implement a custom encoding of the web responce in WCF (see http://msdn.microsoft.com/en-us/library/ms734675.aspx) your WCF method should better return Message instead of void:

[WebGet(UriTemplate = "hello")]
public Message SayHello()
{
    SimpleMessage message = new SimpleMessage() {Message = "Hello World"};
    string myResponseBody = JsonConvert.Serialize(message);
    return WebOperationContext.Current.CreateTextResponse (myResponseBody,
                "application/json; charset=utf-8",
                Encoding.UTF8);
}
CreateStreamResponse
CreateTextResponse
OutgoingWebResponseContext ctx = WebOperationContext.Current.OutgoingResponse;
ctx.StatusCode = HttpStatusCode.BadRequest;

At the end I want repeat my question from a comment: could you explain why you want use Json.Net instead of DataContractJsonSerializer? Is it performance improvement? Do you need implement serialization of some data types like DateTime in other way as DataContractJsonSerializer do? Or the main reason of your choose of Json.Net is some other?

In my web.config, my <standardEndpoint> has defaultOutgoingResponseFormat="Json", so I do not have to specify it in the attribute on the service method. I am using DataContractJsonSerializer correctly, and this is not an issue of how it is displayed in the debugger. I can inspect it in FireBug or Fiddler, and see not only the exact characters that are being sent, but also the content length, so I know just what is included. It is not the same result in both cases; it is what I described in the original question.

The problem is if you goes to jsonlint.com (the site of one of creator of JSON) you can verify that {"Message":"Hello World"} is a valid JSON data, but "{\"Message\":\"Hello World\"}" is not. Try paste in jsonlint.com exact strings which you see in Fiddler/FireBug and you will see whether you have correct JSON. On json.org you will find the JSON specification.

I realize that "{\"Message\":\"Hello World\"}" is not valid "raw" json. It's valid json, passed as a string, so it's wrapped in quotes. Were it to be passed to eval() or JSON.parse(), then it would evaluate just fine, since it is valid json. But, that is neither my issue, nor my question.

What do you mean as you write "I can just return the raw json myself? Without the wrapping quotes?" Do you want probably return {Message:"Hello World"}? But is is wrong JSON (try in jsonlint.com). How do you plan use the data on the client side? If you hold the standard you can just use standard serializer. If you want use compact data you can use binary serializer. If you want just log your object, you can enumerate all object properties and write there. But if you use "JSON" as a format name you have to hold the JSON specification json.org.

OK. Interesting! The information about serialization of graphs that contain cycles is new for me. I have this constructs not, but probably I should look at Json.Net more carefully. By the way, the usage of Massage type can help with input parameters of Web Methods also.

How can I return json from my WCF rest service (.NET 4), using Json.Ne...

wcf rest serialization json.net
Rectangle 27 10

DataContractJsonSerializer
ResponseFormat = ResponseFormat.Json
public SimpleMessage SayHelloObject()

Moreover if you have {"Message":"Hello World"} in a string and display it in debugger it will be display as "{\"Message\":\"Hello World\"}", so exactly like you see string json = JsonConvert.Serialize(message); (Json.Net). So it seems to me that you have in both cases the same results.

To verify this use a client software which read the results. See some examples

UPDATED: In your code you define method SayHelloString(). It's result are a string. If you call the method this string will be one more time JSON serialized. JSON serialization of the string {"Message":"Hello World"} is a quoted string (see http://www.json.org/ definition for not a object, but a string) or exactly string "{\"Message\":\"Hello World\"}". So everything is correct with both methods of your Web Service.

UPDATED 2: I am glad that my tip from "Update" part of my answer helped you to swich of the double JSON serialization.

Nevertheless I would recommend you to change a little the solution to stay more at the WCF concept.

If you want implement a custom encoding of the web responce in WCF (see http://msdn.microsoft.com/en-us/library/ms734675.aspx) your WCF method should better return Message instead of void:

[WebGet(UriTemplate = "hello")]
public Message SayHello()
{
    SimpleMessage message = new SimpleMessage() {Message = "Hello World"};
    string myResponseBody = JsonConvert.Serialize(message);
    return WebOperationContext.Current.CreateTextResponse (myResponseBody,
                "application/json; charset=utf-8",
                Encoding.UTF8);
}
CreateStreamResponse
CreateTextResponse
OutgoingWebResponseContext ctx = WebOperationContext.Current.OutgoingResponse;
ctx.StatusCode = HttpStatusCode.BadRequest;

At the end I want repeat my question from a comment: could you explain why you want use Json.Net instead of DataContractJsonSerializer? Is it performance improvement? Do you need implement serialization of some data types like DateTime in other way as DataContractJsonSerializer do? Or the main reason of your choose of Json.Net is some other?

In my web.config, my <standardEndpoint> has defaultOutgoingResponseFormat="Json", so I do not have to specify it in the attribute on the service method. I am using DataContractJsonSerializer correctly, and this is not an issue of how it is displayed in the debugger. I can inspect it in FireBug or Fiddler, and see not only the exact characters that are being sent, but also the content length, so I know just what is included. It is not the same result in both cases; it is what I described in the original question.

The problem is if you goes to jsonlint.com (the site of one of creator of JSON) you can verify that {"Message":"Hello World"} is a valid JSON data, but "{\"Message\":\"Hello World\"}" is not. Try paste in jsonlint.com exact strings which you see in Fiddler/FireBug and you will see whether you have correct JSON. On json.org you will find the JSON specification.

I realize that "{\"Message\":\"Hello World\"}" is not valid "raw" json. It's valid json, passed as a string, so it's wrapped in quotes. Were it to be passed to eval() or JSON.parse(), then it would evaluate just fine, since it is valid json. But, that is neither my issue, nor my question.

What do you mean as you write "I can just return the raw json myself? Without the wrapping quotes?" Do you want probably return {Message:"Hello World"}? But is is wrong JSON (try in jsonlint.com). How do you plan use the data on the client side? If you hold the standard you can just use standard serializer. If you want use compact data you can use binary serializer. If you want just log your object, you can enumerate all object properties and write there. But if you use "JSON" as a format name you have to hold the JSON specification json.org.

OK. Interesting! The information about serialization of graphs that contain cycles is new for me. I have this constructs not, but probably I should look at Json.Net more carefully. By the way, the usage of Massage type can help with input parameters of Web Methods also.

How can I return json from my WCF rest service (.NET 4), using Json.Ne...

wcf rest serialization json.net
Rectangle 27 0

It sounds like, if as you say everything must be in .NET framework, then you can use Visual Studios to develop this project in VB or C#. Essentially, the page that initially sends the request to the web service would be built as a .aspx webpage. Then you can build a web service in C# or VB .asmx which handles the calculation, returns a result that is parsed by javascript on another asp.net web page and produces a button to send the gathered data as a POST to another URL.

I have some gaps in my knowledge. I know how to create the webservice. What I'd like to understand is, how can the page make a request to that webservice ? Do I need to use some framework (.Net MVC) or what ?

Also, how will it be able to handle the response from the webservice ?

If you'd like you can use a basic HTML form to send a post request to the web service. Check out the "Test" pages for the functions in your web service and view their source code to see what a sample HTML form could look like for your web service. As far as handling a response, you could javascript to parse the response on the page or use ASP.Net functions to parse the response. The response will come back as XML and there are some very nice built in libraries in .NET for handling these.

@brainydexter You could also use some Ajax and updatepanels to do the postback (which means the whole page doesn't refresh) and do the server side processing without the user even knowing.

c# - recommended way to handle this case in .NET for web application -...

c# .net asp.net web-services
Rectangle 27 0

You have two options:

  • You can keep your web service and continue with the same ASPX as your view. This would require little or no modification of your ASPX (changing the master page)
  • You can keep the ASPX and convert the ASMX to controller method which returns JsonResult

If I move my methods from the ASMX to the <tt>Controller</tt>, I should remove the <tt>[WebMethod]</tt> attribute from the method, correct?

Sign up for our newsletter and get our top new questions delivered to your inbox (see an example).

Architecture switch from ASP.NET Page and JSON ASMX Web Services to MV...

asp.net asp.net-mvc web-services architecture asmx
Rectangle 27 0

With standard Android, you can create a JSON Object from your data:

And then parse from a JSON String:

JSONObject jsonObj = new JSONObject(jsonString);
JSONArray jsonPcArray = jsonObj.getJSONArray("percentageArray");
double[] percentageArray = new double[jsonPcArray.length()];
for(int i = 0; i < percentageArray.length; i++) {
    percentageArray[i] = jsonPcArray.getDouble(i);
}

Alternatively, I strongly recommend using either Jackson, or Google's own GSON library, which makes reading/writing JSON as simple as writing a class like this:

class MyClass {
    double[] percentageArray;
}
MyClass obj = gson.fromJson(jsonString, MyClass.class);
String jsonString = gson.toJson(obj)

Error occured in 'JSONObject jsonObj = new JSONObject(jsonString);' because my jsonString is in xml. How can i solve it?

You'll have to parse your XML first, extract the content of the string node, then pass that content to the JSON parsing routine. There's a page on the Android Dev site about how to parse XML: developer.android.com/training/basics/network-ops/xml.html

android - asmx web service can result JSON purely? - Stack Overflow

android .net xml json web-services
Rectangle 27 0

In one of my project for travel industry (around 1m hits per day), we had a separate auth server farm. There were around four load balanced server at that time. Our business layer called the authentication web service (asmx) passing the user credentials and get the xml results. If the number of users increase, we can scale out the auth farm further. IMHO using the web services over the http (on intranet) give more performance benefit than TCP.

asp.net mvc - Design Decision - Scaling out web based application's ar...

asp.net-mvc architecture scalability ipc rpc
Rectangle 27 0

public class CallSoap 
{

public String SOAP_ACTION = "http://tempuri.org/CreateEvent";

public String OPERATION_NAME = "CreateEvent"; 

public  final String WSDL_TARGET_NAMESPACE = "http://tempuri.org/";

public String erorr="";

public  final String SOAP_ADDRESS = "http://xxxx/Service1.asmx";

SoapObject request;
SoapSerializationEnvelope envelope;

//AndroidHttpTransport androidHttpTransport;
HttpTransportSE androidHttp;

public CallSoap() 
{ 
}


protected void SetEnvelope() {

    try {
        StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
        StrictMode.setThreadPolicy(policy); 

        // Creating SOAP envelope           
        envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);

        //You can comment that line if your web service is not .NET one.
        envelope.dotNet = true;

        envelope.setOutputSoapObject(request);
        androidHttp = new HttpTransportSE("xxxx/Service1.asmx");

        androidHttp.debug = true;

    } catch (Exception e) {
        System.out.println("Soap Exception---->>>" + e.toString());    
    }
}

@SuppressLint("SimpldurationFormat")
public int Send(decimal amount, decimal persons)
{
    int id=0;
    try{
            //request
            request = new SoapObject(WSDL_TARGET_NAMESPACE,OPERATION_NAME);

            PropertyInfo pi5=new PropertyInfo();
            pi5.setType(decimal.class);
            pi5.setName("amount");
            pi5.setValue(amount);
            request.addProperty(pi5);

            PropertyInfo pi6=new PropertyInfo();
            pi6=new PropertyInfo();
            pi6.setType(decimal.class);
            pi6.setName("persons");
            pi6.setValue(persons);
            request.addProperty(pi6);

            SetEnvelope();
            //Create envelope
        }
    catch (Exception exception)
        {
        erorr= "error:"+exception.toString();
        }
    try
        {
            androidHttp.call(SOAP_ACTION, envelope);
            //Vector<String> result = null;
            //result = (Vector<String>) envelope.getResponse();
            String result = envelope.getResponse().toString();
            try { 
                id=Integer.parseInt(result); 
            } catch(NumberFormatException e) { 
                erorr=result;
            }
        }
    catch (Exception exception)
        {
        erorr= "error:"+exception.toString();
        }
    }

how to get data from sql server using web service in android - Stack O...

android sql
Rectangle 27 0

return new Gson().toJson(percentageArray);

Nope. In .NET mapping is mostly automatic JSON <-> Object with Rest web services and WebApi.

android - asmx web service can result JSON purely? - Stack Overflow

android .net xml json web-services
Rectangle 27 0

I'd recommend offloading the task to SSRS, which handles long-running queries without a problem. You can build a report with your report builder, then use your .NET app to invoke the SSRS web services run your report and export the results back in Excel format (as a byte array). See this page for sample code using the .asmx service, and this page for invoking SSRS with WCF.

You should also call your webservice in a separate thread to avoid tying up your UI.

.net - What's the best way to transfer a large dataset over an ASMX we...

.net web-services asmx large-data-volumes
Rectangle 27 0

I'm sure your string is wrong. Correct format should be something like this:

{
  "DB": {
    "tbl_ha_kind": [
      {
        "intHAKindID": "1",
        "txtHAKind": "txt1",
        "intHA": "1",
        "intLanguage": "1",
        "intCat": "0"
      },
      {
        "intHAKindID": "3",
        "txtHAKind": "txt2",
        "intHA": "1",
        "intLanguage": "1",
        "intCat": "1"
      },
      {
        "intHAKindID": "6",
        "txtHAKind": "txt3",
        "intHA": "2",
        "intLanguage": "1",
        "intCat": "200"
      },
      {
        "intHAKindID": "7",
        "txtHAKind": "txt4",
        "intHA": "2",
        "intLanguage": "1",
        "intCat": "200"
      },
      {
        "intHAKindID": "9",
        "txtHAKind": "txt5",
        "intHA": "1",
        "intLanguage": "1",
        "intCat": "200"
      },
      {
        "intHAKindID": "10",
        "txtHAKind": "txt6",
        "intHA": "1",
        "intLanguage": "1",
        "intCat": "200"
      }
    ],
    "tbl_medical_kind": [
      {
        "intMedicalKindID": "1",
        "txtMedicalKind": "txt1",
        "txtBackColor": "005AAB",
        "intLanguage": "1",
        "intHA": "1",
        "intPos": "0",
        "intHAKindID": "1"
      },
...
}
try {
                JSONObject jsonObject = new JSONObject(jsonString);
                JSONObject dbObject = jsonObject.getJSONObject("DB");
...

            } catch (JSONException e) {
                Log.e(TAG, e.getMessage());
                e.printStackTrace();
            }

android - asmx web service can result JSON purely? - Stack Overflow

android .net xml json web-services
Rectangle 27 0

public class CallSoap 
{

public String SOAP_ACTION = "http://tempuri.org/CreateEvent";

public String OPERATION_NAME = "CreateEvent"; 

public  final String WSDL_TARGET_NAMESPACE = "http://tempuri.org/";

public String erorr="";

public  final String SOAP_ADDRESS = "http://xxxx/Service1.asmx";

SoapObject request;
SoapSerializationEnvelope envelope;

//AndroidHttpTransport androidHttpTransport;
HttpTransportSE androidHttp;

public CallSoap() 
{ 
}


protected void SetEnvelope() {

    try {
        StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
        StrictMode.setThreadPolicy(policy); 

        // Creating SOAP envelope           
        envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);

        //You can comment that line if your web service is not .NET one.
        envelope.dotNet = true;

        envelope.setOutputSoapObject(request);
        androidHttp = new HttpTransportSE("xxxx/Service1.asmx");

        androidHttp.debug = true;

    } catch (Exception e) {
        System.out.println("Soap Exception---->>>" + e.toString());    
    }
}

@SuppressLint("SimpldurationFormat")
public int Send(decimal amount, decimal persons)
{
    int id=0;
    try{
            //request
            request = new SoapObject(WSDL_TARGET_NAMESPACE,OPERATION_NAME);

            PropertyInfo pi5=new PropertyInfo();
            pi5.setType(decimal.class);
            pi5.setName("amount");
            pi5.setValue(amount);
            request.addProperty(pi5);

            PropertyInfo pi6=new PropertyInfo();
            pi6=new PropertyInfo();
            pi6.setType(decimal.class);
            pi6.setName("persons");
            pi6.setValue(persons);
            request.addProperty(pi6);

            SetEnvelope();
            //Create envelope
        }
    catch (Exception exception)
        {
        erorr= "error:"+exception.toString();
        }
    try
        {
            androidHttp.call(SOAP_ACTION, envelope);
            //Vector<String> result = null;
            //result = (Vector<String>) envelope.getResponse();
            String result = envelope.getResponse().toString();
            try { 
                id=Integer.parseInt(result); 
            } catch(NumberFormatException e) { 
                erorr=result;
            }
        }
    catch (Exception exception)
        {
        erorr= "error:"+exception.toString();
        }
    }

how to get data from sql server using web service in android - Stack O...

android sql
Rectangle 27 0

You have many possible ways to do that. One of the ways is to use html with jquery and send the result via web service (.asmx for instance) and save that result in a database (MSSQL for instance). So everytime you load the page you can get those saved results and display it on the relevant page. Another way is to use php with mysql or to use java...

If you don't want to use databases and server side code you can save the results in a cookie and then display those results in the page.

javascript - how to save changes on website with textbox - Stack Overf...

javascript html
Rectangle 27 0

Your problem is that you have XML tags around your JSON, i.e. your JSON is returned inside XML.

I suspect you just requested an incorrect mime type from your web service (application/xml instead of application/json).

says that you're using an obsolete technology and that it's not trivial making it return JSON. It returns XML by design.

Perhaps you could make it produce XML indeed and then parse it as XML on the Android side?

In any case, you should see the answers in that thread.

please let me know where can I search application/xml to change as you said.I am absolute beginner so please help me.Anyway thank you.

I now see that I misread your question. Please unaccept it. You're actually trying to create a JSON output, not parse it, right? In that case, you should see kayz1's answer. You can see how to add the GSON library to your project here: stackoverflow.com/questions/11961605/

Yes!I want to create a JSON output without XML.How can I do in server application (.Net)?

Show us the code you have that produces the XML output that you're now using.

Already shown GetGrowthPersentage() that produces the XML output.

android - asmx web service can result JSON purely? - Stack Overflow

android .net xml json web-services