Android Question Parse json result

Douglas Farias

Expert
Licensed User
Longtime User
Hi all.
later many try*s i will request some help..

how can i parse this json result ?

{"success":true,"resultado":{"1":{"date":"29\/11\/2016 18:38","site":"CEE NOVO HAMBURGO - Novo Hamburgo\/RS","status":"Entrega Efetuada","isOrigin":true},"2":{"date":"29\/11\/2016 09:47","site":"Novo Hamburgo\/RS","status":"Saiu para entrega ao destinat\u00e1rio","isOrigin":true},"3":{"date":"28\/11\/2016 22:14","site":"CTE PORTO ALEGRE - Porto Alegre\/RS","status":"Encaminhado","isOrigin":true},"4":{"date":"28\/11\/2016 22:14","site":"Encaminhado para CEE NOVO HAMBURGO - Novo Hamburgo\/RS","status":"Encaminhado","isOrigin":false},"5":{"date":"25\/11\/2016 22:19","site":"CTE CAMPINAS - INDAIATUBA\/SP","status":"Encaminhado","isOrigin":true},"6":{"date":"25\/11\/2016 22:19","site":"Em tr\u00e2nsito para CTE PORTO ALEGRE - Porto Alegre\/RS","status":"Encaminhado","isOrigin":false},"7":{"date":"25\/11\/2016 18:01","site":"AC JUNDIAI - Jundiai\/SP","status":"Encaminhado","isOrigin":true},"8":{"date":"25\/11\/2016 18:01","site":"Encaminhado para UNIDADE DE CORREIOS\/BR","status":"Encaminhado","isOrigin":false},"9":{"date":"25\/11\/2016 13:01","site":"AC JUNDIAI - Jundiai\/SP","status":"Postado","isOrigin":true}},"Contador":9}


I know that json is badly formatted, but I have to find some solution to get the data as it is at the moment.


here is my last try code

B4X:
      Select Job.JobName
         Case "jobrastreio"
             listaResultadoRastreio.Clear
            Dim parser As JSONParser
            parser.Initialize(Job.GetString)
            Dim root As Map = parser.NextObject
            Dim success As String = root.Get("success")
            Dim Contador As Int = root.Get("Contador")
            Dim resultado As Map = root.Get("resultado")
            Log(resultado)
            Log(resultado.Get("1"))
           
                For i = 0 To Contador
                     Dim mm As Map = resultado.Get(i)
                     Log(mm.Size)
                     Dim date As String = mm.Get("date")
                     Dim site As String = mm.Get("site")
                     Dim isOrigin As String = mm.Get("isOrigin")
                     Dim status As String = mm.Get("status")
                     Log(status)
                Next

but dont works, on the for i = 0 the map mm is not initialized.
thats is strange, because this look a map

{date=29/11/2016 18:38, site=CEE NOVO HAMBURGO - Novo Hamburgo/RS, status=Entrega Efetuada, isOrigin=true}

how can i parse this result?
ps: the result size is diferent
The result may be different always, in this case we have 9 items, but may be other values.

on the Erel website
http://www.b4x.com:51042/json/index.html

the code dont parse correct, i think because the json code is bad formated

any help is welcome.
thank you
 

KMatle

Expert
Licensed User
Longtime User
{date=29/11/2016 18:38, site=CEE NOVO HAMBURGO - Novo Hamburgo/RS, status=Entrega Efetuada, isOrigin=true}

A map looks like this:

B4X:
{date:"29/11/2016 18:38", site:"CEE NOVO HAMBURGO - Novo Hamburgo/RS", status:"Entrega Efetuada", isOrigin:"true"}

B4X:
Dim parser As JSONParser
parser.Initialize(<text>)
Dim root As Map = parser.NextObject
Dim date As String = root.Get("date")
Dim site As String = root.Get("site")
Dim isOrigin As String = root.Get("isOrigin")
Dim status As String = root.Get("status")
 
Upvote 0

DonManfred

Expert
Licensed User
Longtime User
I know that json is badly formatted, but I have to find some solution to get the data as it is at the moment.
Where is the code which creates this json? It needs to be updated to return a correct json
 
Upvote 0

Douglas Farias

Expert
Licensed User
Longtime User
A map looks like this:

B4X:
{date:"29/11/2016 18:38", site:"CEE NOVO HAMBURGO - Novo Hamburgo/RS", status:"Entrega Efetuada", isOrigin:"true"}

B4X:
Dim parser As JSONParser
parser.Initialize(<text>)
Dim root As Map = parser.NextObject
Dim date As String = root.Get("date")
Dim site As String = root.Get("site")
Dim isOrigin As String = root.Get("isOrigin")
Dim status As String = root.Get("status")
ty i will try


Where is the code which creates this json? It needs to be updated to return a correct json
the code is here, i really dont know php to format this
https://github.com/QuatroDigital/Correios-SRO-to-JSON/blob/master/qd-correios-sro-2-json.php
 
Upvote 0

DonManfred

Expert
Licensed User
Longtime User
i really dont know php to format this
if you have control over this php you can try

PHP:
<?php
/**
 * Quatro Digital - Correios SRO to JSON
 *
 * Este script lê a página de rastreamento dos Correios com base em código de rastreio informado via GET ou POST
 * e a transforma em JSON ou JSONP
 *
 * @version 1.1
 * @author Carlos Vinicius
 * @license MIT <http://opensource.org/licenses/MIT>
 */
try {
   include("helpers/simple_html_dom.php");
   $correiosSRO = file_get_html("http://websro.correios.com.br/sro_bin/txect01$.QueryList?P_ITEMCODE=&P_LINGUA=001&P_TESTE=&P_TIPO=001&Z_ACTION=Search&P_COD_UNI=" . strtoupper(trim($_REQUEST["tracking"])));
   $out = array();
   function getSroArray($table) {
     foreach ($table->find("tr") as $k => $row) {
     // Removendo a linha de título/cabeçalho da tabela
       if($k == 0)
         continue;
     // DATA
     // Armazenando a informação de data caso ela ainda não exista
       $dateExists = false;
       $date = $row->find("td", 0);
       if(!isset($out[$k]["date"])){
         $out[$k]["date"] = utf8_encode($date->plaintext);
         $dateExists = true;
       }
     // Quando a célula possui colspan, coloco a data para as demais linhas
       $rowSpan = $date->rowspan;
       if($rowSpan > 1){
         for($i = 1; $i < $rowSpan; $i++)
           $out[$k + $i]["date"] = $out[$k]["date"];
       }
     // DESCRIÇÃO
     // Armazenando a descrição do estado de rastreio
       $site = $row->find("td", $dateExists ? 1 : 0);
       $out[$k]["site"] = is_object($site) ? utf8_encode($site->plaintext) : false;
     // STATUS
     // Armazenando as informações de situação do pedido
       $status = $row->find("td", $dateExists ? 2 : 1);
       $statusValue = is_object($status) ? utf8_encode($status->plaintext) : false;
       $out[$k]["status"] = $statusValue;
     // Quando a descrição possui colspan eu copio a informação de status existente na linha anterior
       if($site->colspan > 1)
         $out[$k]["status"] = $out[$k - 1]["status"];
     // Informo se a linha é a origem da informação ou o destino
       $out[$k]["isOrigin"] = $statusValue === false? false: true;
     }
     return $out;
   }
   // Busco a tabela no conteúdo da requisição feita aos correios
   $sroTable = $correiosSRO->find('table', 0);
   // Caso a tabela exista, faço o processamento
   if($sroTable){
     $arrayOut = getSroArray($sroTable);
    $mout = array();
     foreach ($arrayOut as $row) {
      $mout[] = $row;
     }
  $arrayOut = $mout;
  // Caso não exista, retorno uma informação de dados não encontrados
   } else {
     $arrayOut = array("emptyResult" => true);
  }
}
catch (Exception $e) {
   $arrayOut = array("error" => $e->getMessage());
   header('HTTP/1.1 500 Internal Server Error');
}
// Defino os headers da requisção
header("Content-Type: application/json");
header('Access-Control-Allow-Origin: *');
// Saída na tela
if(isset($_REQUEST["callback"]))
   echo $_REQUEST["callback"] . "(" . json_encode($arrayOut) . ");";
else
   echo json_encode($arrayOut);
?>

The problem is that the phpscript ises the numeric indexes of an array... to work with it is ok. But to return the result with json it will fail.

The interesting lines in the code i posted are

PHP:
     $arrayOut = getSroArray($sroTable);
    $mout = array();
     foreach ($arrayOut as $row) {
      $mout[] = $row;
     }
  $arrayOut = $mout;

I´m not sure it will work but i guess it will.

It will iterate through your array finding all root objects... which are numbered... 0,1,2,3,and so on...

it will get all "Rows" and add them to the newly created Array $mout;

I´m pretty sure when $arrayOut later in the code run through
PHP:
    echo json_encode($arrayOut);
it will return a better formatted json.
 
Upvote 0

Douglas Farias

Expert
Licensed User
Longtime User
if you have control over this php you can try

PHP:
<?php
/**
* Quatro Digital - Correios SRO to JSON
*
* Este script lê a página de rastreamento dos Correios com base em código de rastreio informado via GET ou POST
* e a transforma em JSON ou JSONP
*
* @version 1.1
* @author Carlos Vinicius
* @license MIT <http://opensource.org/licenses/MIT>
*/
try {
   include("helpers/simple_html_dom.php");
   $correiosSRO = file_get_html("http://websro.correios.com.br/sro_bin/txect01$.QueryList?P_ITEMCODE=&P_LINGUA=001&P_TESTE=&P_TIPO=001&Z_ACTION=Search&P_COD_UNI=" . strtoupper(trim($_REQUEST["tracking"])));
   $out = array();
   function getSroArray($table) {
     foreach ($table->find("tr") as $k => $row) {
     // Removendo a linha de título/cabeçalho da tabela
       if($k == 0)
         continue;
     // DATA
     // Armazenando a informação de data caso ela ainda não exista
       $dateExists = false;
       $date = $row->find("td", 0);
       if(!isset($out[$k]["date"])){
         $out[$k]["date"] = utf8_encode($date->plaintext);
         $dateExists = true;
       }
     // Quando a célula possui colspan, coloco a data para as demais linhas
       $rowSpan = $date->rowspan;
       if($rowSpan > 1){
         for($i = 1; $i < $rowSpan; $i++)
           $out[$k + $i]["date"] = $out[$k]["date"];
       }
     // DESCRIÇÃO
     // Armazenando a descrição do estado de rastreio
       $site = $row->find("td", $dateExists ? 1 : 0);
       $out[$k]["site"] = is_object($site) ? utf8_encode($site->plaintext) : false;
     // STATUS
     // Armazenando as informações de situação do pedido
       $status = $row->find("td", $dateExists ? 2 : 1);
       $statusValue = is_object($status) ? utf8_encode($status->plaintext) : false;
       $out[$k]["status"] = $statusValue;
     // Quando a descrição possui colspan eu copio a informação de status existente na linha anterior
       if($site->colspan > 1)
         $out[$k]["status"] = $out[$k - 1]["status"];
     // Informo se a linha é a origem da informação ou o destino
       $out[$k]["isOrigin"] = $statusValue === false? false: true;
     }
     return $out;
   }
   // Busco a tabela no conteúdo da requisição feita aos correios
   $sroTable = $correiosSRO->find('table', 0);
   // Caso a tabela exista, faço o processamento
   if($sroTable){
     $arrayOut = getSroArray($sroTable);
    $mout = array();
     foreach ($arrayOut as $row) {
      $mout[] = $row;
     }
  $arrayOut = $mout;
  // Caso não exista, retorno uma informação de dados não encontrados
   } else {
     $arrayOut = array("emptyResult" => true);
  }
}
catch (Exception $e) {
   $arrayOut = array("error" => $e->getMessage());
   header('HTTP/1.1 500 Internal Server Error');
}
// Defino os headers da requisção
header("Content-Type: application/json");
header('Access-Control-Allow-Origin: *');
// Saída na tela
if(isset($_REQUEST["callback"]))
   echo $_REQUEST["callback"] . "(" . json_encode($arrayOut) . ");";
else
   echo json_encode($arrayOut);
?>

The problem is that the phpscript ises the numeric indexes of an array... to work with it is ok. But to return the result with json it will fail.

The interesting lines in the code i posted are

PHP:
     $arrayOut = getSroArray($sroTable);
    $mout = array();
     foreach ($arrayOut as $row) {
      $mout[] = $row;
     }
  $arrayOut = $mout;

I´m not sure it will work but i guess it will.

It will iterate through your array finding all root objects... which are numbered... 0,1,2,3,and so on...

it will get all "Rows" and add them to the newly created Array $mout;

I´m pretty sure when $arrayOut later in the code run through
PHP:
    echo json_encode($arrayOut);
it will return a better formatted json.
thx worked fine.
sended 5$ for u, many thx


Just took a look. They use "$row->find(....)" which is far away from a good structure (I assume they don't understand JSON).
yes, bad formated code, i dont know php but i can imagine>
i found this on github, it is needed on my new project, forcing me use this code :(
 
Upvote 0
Top