Connect UWP C # to remote MySQL

2

MY CASE

I am trying to connect my Universal Application (UWP) to my website (PHP) which performs queries to my database (MySQL). The results returned by PHP are JSON strings which I have to PARSE in my app through JsonObject .

WHAT WORKS
1. Connection to the website (ok).
2. SQL queries (ok).
3. Return of JSON strings (ok).

THE CODES
JSON strings returned by PHP.

Modelo A: "{'CAT':'LOG','MSG':'OK','SUBB':{'ID':'U1','USU':'JORNY'}}";  
Modelo B: "{'CAT':'LOG','MSG':'ER','SUBB':'-'}";

Function that parses the JSON string in C # (UWP)

private async void Consultar(object sender, RoutedEventArgs e) {
    /*Capturo los reultados devueltos por PHP*/
    string CadenaJSON = await AccessTheWebAsyncPost();
    /*reemplazo comillas simples por dobles, esta parte lo hago así
      porque C# devuelve error de JSON no válido*/
    string contentLength = CadenaJSON.Replace("'", "\"");
    /*parseo a traves de JsonObject la cadena*/
    JsonObject jsonObject = JsonObject.Parse(contentLength);
    /*leo las secciones CAT y SUBB*/
    string sCat = jsonObject["CAT"].GetString();
    string sSubb = jsonObject["SUBB"].GetString();/*<---- El error ocurre aquí*/
    /*muestro los resultados*/
    txtCat.Text = sCat.ToString();
    txtSubb.Text = sSubb.ToString();
}  

WHAT DOES NOT WORK
1. The parsing of JSON strings works very well when PHP returns model B, but when it returns model A, it sends an error.
I guess it's because model A has internal sections within SUBB but model B does not.

THE ERROR

    
asked by Jorny 17.04.2017 в 16:32
source

1 answer

1

I was finally able to fix it, thanks to the user @Pikoh. I publish the solution with the already improved code, I hope it serves you. Good luck;).

private async void Consultar(object sender, RoutedEventArgs e) {
    /*variables para almacenar secciones de JSON*/
    string sCat = "", sMen = "", sSubb = "";
    string sId  = "", sUsu = "";
    /*Capturar cadena JSON devuelta por PHP*/
    string JsonPHP = await AccessTheWebAsyncPost();
    /*Reemplazar comillas simples por dobles, esto es exigencia de C#*/
    string JsonSharp = JsonPHP.Replace("'", "\"");
    /*Crear objeto Json parseando la cadena JsonSharp*/
    JsonObject objJson = JsonObject.Parse(JsonSharp);
    /*leer secciones del Json*/
    sCat = objJson["CAT"].GetString();
    sMen = objJson["MSG"].GetString();
    /*la seccion SUBB en algunos casos devuelve un JSON interno,
      de ser el caso es un Object, sino, es un String*/
    if (objJson["SUBB"].ValueType == JsonValueType.String)    {
        /*si es un string*/
        sSubb = objJson["SUBB"].GetString();
    }  else  {
        /*si es un object*/
        sId  = objJson["SUBB"].GetObject().GetNamedString("ID"); 
        sUsu = objJson["SUBB"].GetObject().GetNamedString("USU");
    }
    /*mostrar resultado*/
    txtId.Text  = sId.ToString();
    txtUsu.Text = sUsu.ToString();
    /*proceso finalizado*/
    txtEstado.Text = "Proceso finalizado.";
}

DE PASADITA
I put the rest of the code, so they can implement it in their UWP App with C #

async Task<String> AccessTheWebAsyncPost()        {
    var values = new Dictionary<string, string>();
    values.Add("VALOR1", "dato_cualquiera");
    values.Add("VALOR2", "dato_cualquiera");
    var content = new FormUrlEncodedContent(values);

    HttpClient client = new HttpClient();
    var httpResponseMessage = await client.PostAsync("http://sitio.com/prueba.php", content);
    Task<string> getStringTask = httpResponseMessage.Content.ReadAsStringAsync();
    DoIndependentWork();
    string urlContents = await getStringTask;
    return urlContents.ToString();
}

void DoIndependentWork()  {
    txtEstado.Text = "Consultando...";
}

THE PART OF PHP

<?php
    if(isset($_POST['VALOR1']) and isset($_POST['VALOR2'])){
        $sV1 = $_POST['VALOR1'];
        $sV2 = $_POST['VALOR2'];

        /*devolución de cadena JSON, donde la sección SUBB contiene otro JSON*/
        echo "{'CAT':'LOG','MSG':'OK','SUBB':{'ID':'un_valor','USU':'un_valor'}}";  
        /*devolución de cadena JSON, donde la sección SUBB NO contiene otro JSON*/
        echo "{'CAT':'LOG','MSG':'ER','SUBB':'-'}";
    }
?>  
    
answered by 17.04.2017 / 18:08
source