Receive and Send JSON C#

Asked

Viewed 574 times

2

In a local application "Windowsform" in C#, I need to send and receive data via JSON to a PHP page, there is some predefined function for this ?

  • Young man, explain better what you want to do. By the way, what PHP tag does in this question?

  • Where I need to send and receive JSON is a PHP page

  • Okay, and what are you doing in C#? Is it a web page? An app console? You need to [Dit] your question and add more details, otherwise your post may be closed because it is unclear...

  • Do you know the basics of this? Read the first results to get a sense of what you’re doing: https://goo.gl/sq9Az8

1 answer

0


Practically you need some statements for your Webservices to work.

[Scriptmethod(Responseformat = Responseformat.Json)]

Specifies the HTTP verb is used to call a method and the answer format. This class cannot be inherited. Details

Javascriptserializer

Json.NET should be used for serialization and deserialization. Provides serialization and deserialization functionality for applications that use AJAX. Details

writeJsonData

And a method that mounts your JSON (Sponse), for example: writeJsonData

See details of a XML Web Services from Windows Forms and Link to a Web Service using Bindingsource from Windows Forms

[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
[WebMethod()]
public void DadosUsuario(String IdUsuario, String Chave)
{
    using (var DBCtx = new WdbContext())
    {
        try
        {
            var Usuario = DBCtx.tb_Usuarios.FirstOrDefault();
            if (Usuario != null)
                RetornarJson(DBCtx, Usuario);  
        }
        catch (Exception exc)
        {
        }
    }
}

private void RetornarJson(WdbContext DBCtx, tb_Usuarios Usu)
{
    string RespJson = String.Empty;

    JavaScriptSerializer js = new JavaScriptSerializer();
    RespJson = js.Serialize(Usu);
    writeJsonData(RespJson);            
}

protected void writeJsonData(string s)
{
    HttpContext context = this.Context;
    HttpResponse response = context.Response;
    context.Response.ContentType = "application/json";
    byte[] b = response.ContentEncoding.GetBytes(s);
    response.AddHeader("Content-Length", b.Length.ToString());
    response.BinaryWrite(b);
    try
    {
        this.Context.Response.Flush();
        this.Context.Response.Close();
    }
    catch (Exception) { }
}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.