Visualizzazione post con etichetta JSon. Mostra tutti i post
Visualizzazione post con etichetta JSon. Mostra tutti i post

venerdì 11 febbraio 2022

Rest Client in Python

Dopo la versione in Go la medesima funzione in Python 


import requests
from requests.structures import CaseInsensitiveDict
import json

url = "http://xxxxxxxxxxxxx/api/v1/authentication/"

headers = CaseInsensitiveDict()


headers["api-key"] = "apikey"
headers["Accept"] = "application/json"
headers["api-version"] = "v1"
headers["device-language"] = "it"
headers["id-user-session"] = "guest"
headers["Authorization"] = "Basic Z2xxxxxxxxxxxxxxxxxxxxxxxxxxx=="



resp = requests.get(url, headers=headers)

print(resp.content)
if(resp.ok):
    jData = json.loads(resp.content)

    print("The response contains {0} properties".format(len(jData)))
    print("\n")
    for key in jData:
        print(str(key) + " : " + str(jData[key]))
else:
    resp.raise_for_status()

Rest client in GO

Un semplice di client di servizio Restful con GO


package main

import (
    "fmt"
    "io/ioutil"
    "log"
    "net/http"
)

func main() {
    client := http.Client{}
    req, err := http.NewRequest("GET", "http://xxxxxxxxxxxxxxxxx/api/v1/authentication/", nil)
    if err != nil {
        //Handle Error
    }

    req.Header = http.Header{
        "Host":                  []string{"http://xxxxxxxxxxxxxxxxxx/api/v1/authentication/"},
        "api-key":         []string{"axxxxxxxxxxxx"},
        "api-version":     []string{"v1"},
        "device-language": []string{"it"},
        "id-user-session": []string{"guest"},
        "Accept":                []string{"application/json"},
        "Authorization":         []string{"Basic Z2lvxxxxxxxxxxxxxxsaQ=="},
    }

    res, err := client.Do(req)

    if err != nil {
        fmt.Errorf("got error")
    } else {
        //fmt.Println("--------------------------")
        //fmt.Println(res)
    }
    defer res.Body.Close()

    b, err := ioutil.ReadAll(res.Body)
    if err != nil {
        log.Fatalln(err)
    }

    fmt.Println(string(b))
}

JSon in Go

 Leggere Json in Go non e' esattamente banale perche' il linguaggio e' fortemente tipizzato

Se il tracciato record del Json e' fissato e' conosciuto si puo' fare un Unmarshal del tracciato altrimenti con Json dinamici o non conosciuti la situazione diventa piu' complessa

Partiamo da un Json complesso

---------------------------------------------------------------------------

 {
        "statusCode":200,
        "message":"OK",
        "dataValue":
            {
                "versionWS":"v1",
                "language":"it",
                "idUserSession":
                "wguest",
                "user":
                    {
                        "userId":27,
                        "userName":"G",
                        "userSurname":"G",
                        "idUserSession":"c4cefc3032e3f8e63f3ee320b81cf1d5"
                    }
            }
    }

---------------------------------------------------------------------------

per fare l'Unmarshal del Json si deve definire tramite Struct il tracciato record con indicato anche il tipo di variabile associata ad ogni campo...in questo campo essendoci piu' livelli si devono creare delle Struct intermedie per i livelli piu' interni. Da notare che le variabilenelle Struct hanno la prima lettera maiuscola per l'esportazione ed il tag Json corrispondente

Interessa arriva a leggere la proprieta' idUserSession dell'utente (si tratta di gestire una authorization da un servizio Restful)

---------------------------------------------------------------------------

package main

import (
    "encoding/json"
    "fmt"
)

type User struct {
    UserId        int32  `json:"userId"`
    UserName      string `json:"userName"`
    UserSurname   string `json:"userSurname"`
    IdUserSession string `json:"idUserSession"`
}

type dataValue struct {
    VersionWS            string `json:"versionWS"`
    Language             string `json:"it"`
    IdUserSession        string `json:"idUserSession"`
    Wguest string `json:"wguest"`
    User                 User   `json:"user"`
}

type messaggio struct {
    StatusCode int32     `json:"statusCode"`
    Message    string    `json:"message"`
    DataValue  dataValue `json:"dataValue"`
}

func main() {
    b := []byte(`    {
        "statusCode":200,
        "message":"OK",
        "dataValue":
            {
                "versionWS":"v1",
                "language":"it",
                "idUserSession":"",
                "guest":"",
                "user":
                    {
                        "userId":27,
                        "userName":"G",
                        "userSurname":"G",
                        "idUserSession":"c"
                    }
            }
    }`)
    var mes messaggio
    json.Unmarshal(b, &mes)
    fmt.Println(mes.DataValue.User.IdUserSession)

}

---------------------------------------------------------------------------

fino a qui e' abbastanza lineare. Senza il tracciato record non si puo' fare Unmarshal di una Struct ma si deve passare attraverso una interface e gestire i vari livelli di map fino a trovare il valore richiesto


---------------------------------------------------------------------------
package main

import (
    "encoding/json"
    "fmt"
)

func main() {
    b := []byte(`    {
        "statusCode":200,
        "message":"OK",
        "dataValue":
            {
                "versionWS":"v1",
                "language":"it",
                "idUserSession":"":
                "guest":"",
                "user":
                    {
                        "userId":27,
                        "userName":"G",
                        "userSurname":"G",
                        "idUserSession":"c"
                    }
            }
    }`)

    var dat map[string]interface{}

    if err := json.Unmarshal(b, &dat); err != nil {
        panic(err)
    }
    test := dat["dataValue"].(map[string]interface{})["user"]
    if rec, ok := test.(map[string]interface{}); ok {
        for key, val := range rec {
            if key == "idUserSession" {
                fmt.Printf(" %s = %s", key, val)
                fmt.Println()
            }

        }
    }

}

---------------------------------------------------------------------------



giovedì 2 aprile 2020

JSON con GSON e Kotlin

Per leggere un file Json con Kotlin si puo' utilizzare la libreria GSON aggiungendo il gradle.build la seguente linea
implementation 'com.google.code.gson:gson:2.8.6'
facciamo per esempio che il file JSON ha il seguente tracciato

    val json = "{'cicli':26,'soglia': 1.5}"
si deve creare una classe che ricostruisce il tracciato record e crea dei metodi per leggere le proprieta'
class imposta(
var cicli:Int = 0,
var soglia:Float = 0.0f) {
fun Get_cicli():Int {
return cicli
}

fun Get_soglia():Float {
return soglia
}
override fun toString(): String {
return "${this.cicli}, ${this.soglia}"
}
}

dopo si cio' si puo' chiamare la funzione .fromJson per poter popolare le variabili
override fun onCreate(savedInstanceState: Bundle?) {
...........

val json = "{'cicli':26,'soglia': 1.5}"


var impostazioni = Gson().fromJson(json, imposta::class.java)
var prova = impostazioni.Get_cicli()
Log.d(
"imposta", impostazioni.toString())
Log.d(
"imposta", prova.toString())



venerdì 28 dicembre 2018

Scrivere Json File in ElectronJS

Un esempio di come salvare i dati in formato JSon in un progetto ElectronJS

Prima viene creato un nuovo oggetto vuoto e successivamente si inseriscono le coppie chiave-valore per popolare l'oggetto, l'oggetto viene poi convertito in una stringa Json con stringify ed infine la stringa viene salvata sul filesystem

===============================================================
      var sinkhole = {};
      sinkhole.localita = sessionStorage.getItem("localita");
      sinkhole.comune = sessionStorage.getItem("comune");
      sinkhole.data = sessionStorage.getItem("data");
      sinkhole.ora = sessionStorage.getItem("ora");
      sinkhole.compilatore = sessionStorage.getItem("compilatore");
      sinkhole.annotazioni = sessionStorage.getItem("annotazioni");
      sinkhole.nord = sessionStorage.getItem("nord");
      sinkhole.est = sessionStorage.getItem("est");
      sinkhole.sistema = sessionStorage.getItem("sistema");

      sinkhole.diametro = diametro;
      sinkhole.deformazione = deformazione;
      sinkhole.pericolo = pericolo;
      sinkhole.elemento = elemento;
      
      var esportazione = JSON.stringify(sinkhole);

      const fs = require('fs');
      var nome_file = sessionStorage.getItem("comune")+"_"+sessionStorage.getItem("ora")+".json";
      fs.writeFile(nome_file, esportazione, (err) => {
        if(err){
            alert("An error ocurred creating the file "+ err.message)
        }
        else {
          alert("File salvato come " + nome_file);
        }
      });

venerdì 20 ottobre 2017

Scrittura JSON su Android N

Un esempio semplice per scrivere un file JSON e gestire in permessi di scrittura su Android 7 e successivi
Nel codice le parti in azzurro sono quelle relative alla gestione dei permessi mentre quelle in giallo sono per la gestione della creazione del JSON


---------------------------------------
<?xml version="1.0" encoding="utf-8"?><manifest xmlns:android="http://schemas.android.com/apk/res/android"    package="com.example.lucainnocenti.jsontester">
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
    <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />



    <application        android:allowBackup="true"        android:icon="@mipmap/ic_launcher"        android:label="@string/app_name"        android:roundIcon="@mipmap/ic_launcher_round"        android:supportsRtl="true"        android:theme="@style/AppTheme">
        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>

---------------------------------------


---------------------------------------
package com.example.lucainnocenti.jsontester;

import android.Manifest;
import android.content.pm.PackageManager;
import android.os.Environment;
import android.support.v4.app.ActivityCompat;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.JsonWriter;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.UnsupportedEncodingException;


public class MainActivity extends AppCompatActivity {
    private int requestCode;
    private int grantResults[];
    private FileOutputStream out;
    private JsonWriter writer;
    private File card;
    private File file;

    @Override    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, requestCode);
        onRequestPermissionsResult(requestCode, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, grantResults);
        Button pulsante =(Button) findViewById(R.id.button);
        pulsante.setOnClickListener(new View.OnClickListener() {
            @Override            public void onClick(View view) {
                card = Environment.getExternalStorageDirectory();
                file = new File (card.getAbsolutePath(),"dati.json");
                try {
                    out = new FileOutputStream(file);
                } catch (FileNotFoundException e) {
                    e.printStackTrace();
                }
                try {
                    writer = new JsonWriter(new OutputStreamWriter(out,"UTF-8"));
                } catch (UnsupportedEncodingException e) {
                    e.printStackTrace();
                }
                try {
                    writer.beginObject();
                } catch (IOException e) {
                    e.printStackTrace();
                }
                try {
                    writer.name("nome").value("Luca");
                    writer.name("cognome").value("Innocenti");
                } catch (IOException e) {
                    e.printStackTrace();
                }

                try {
                    writer.endObject();
                } catch (IOException e) {
                    e.printStackTrace();
                }
                try {
                    writer.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
                ;


            }
        });
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) {
        switch (requestCode) {
            case 1: {

                // If request is cancelled, the result arrays are empty.                if (grantResults.length > 0
                        && grantResults[0] == PackageManager.PERMISSION_GRANTED) {

                    Log.d("permission", "granted");
                } else {


                    Toast.makeText(MainActivity.this, "Permission denied to read your External storage", Toast.LENGTH_SHORT).show();

                    onDestroy();
                }
                return;
            }
        }
    }
}

mercoledì 23 aprile 2014

JSON da Mysql ad Android

Per poter effettuare lo scambio dati (unidirezionale) tra un server ed un client mobile Android puo' essere utile impiegare JSon

Per prima cosa si deve configurare il lato server installando Apache,Php e le sue estensioni (in particolare php5-json) e mysql


sudo apt-get install apache2
sudo apt-get install php5
sudo apt-get install libapache2-mod-php5
sudo apt-get install php5-json
sudo /etc/init.d/apache2 restart
sudo apt-get install mysql-server phpmyadmin

A questo punto si crea la base dati. Nell'esempio e' stato creato un database "test" con una sola tabella "test" con una struttura di questo tipo
----------------------------------------------------
-- phpMyAdmin SQL Dump
-- version 3.4.10.1deb1
-- http://www.phpmyadmin.net
--
-- Host: localhost
-- Generation Time: Apr 23, 2014 at 04:15 PM
-- Server version: 5.5.35
-- PHP Version: 5.3.10-1ubuntu3.11

SET SQL_MODE="NO_AUTO_VALUE_ON_ZERO";
SET time_zone = "+00:00";


/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */;
/*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */;
/*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */;
/*!40101 SET NAMES utf8 */;

--
-- Database: `test`
--

-- --------------------------------------------------------

--
-- Table structure for table `test`
--

CREATE TABLE IF NOT EXISTS `test` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `nome` varchar(50) NOT NULL,
  `cognome` varchar(50) NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB  DEFAULT CHARSET=latin1 AUTO_INCREMENT=3 ;

--
-- Dumping data for table `test`
--

INSERT INTO `test` (`id`, `nome`, `cognome`) VALUES
(1, 'Luca', 'Innocenti'),
(2, 'Alessio', 'Parauda');

/*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */;
/*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */;
/*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;
----------------------------------------------------

per interrogare il db sul lato server e' stato inserito il seguente semplice script Python che effettua una query e crea un oggetto JSon con i dati risultanti dalla query
----------------------------------------------------
<?php
$mysql_db_hostname = "localhost";
$mysql_db_user = "xxxxx";
$mysql_db_password = "xxxxxx";
$mysql_db_database = "test";

$con = @mysqli_connect($mysql_db_hostname, $mysql_db_user, $mysql_db_password,$mysql_db_database);

if (!$con) {
echo('Could not connect to MySQL: ' . mysqli_connect_error());
}

$var = array();
$sql = "SELECT * FROM test";

$result = mysqli_query($con, $sql);
while($obj = mysqli_fetch_object($result)) {
$var[] = $obj;
}
echo json_encode($var);
?>
----------------------------------------------------
si puo' testare l'output chiamando la pagina da browser


L'applicazione Android di seguito riportata apre una connessione Http verso la pagina php precedentemente predisposta ed effettua il parsing dell'oggetto JSon
Ovviamente deve essere impostato nel file Manifest il permesso per l'uso di Internet

----------------------------------------------------
package com.luca.json;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.StatusLine;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.support.v7.app.ActionBarActivity;
import android.support.v4.app.Fragment;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;


public class MainActivity extends ActionBarActivity {

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);

 
setContentView(R.layout.activity_main);

if (savedInstanceState == null) {
getSupportFragmentManager().beginTransaction()
.add(R.id.container, new PlaceholderFragment()).commit();
}

Thread thread = new Thread(new Runnable(){
   @Override
   public void run() {
     String result = readJson();
     JSONArray jArray = null;
try {
jArray = new JSONArray(result);
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
     JSONObject json_data=null;
       for(int i=0;i<jArray.length();i++){
               try {
json_data = jArray.getJSONObject(i);
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
               try {
String nr = Integer.toString(json_data.getInt("id"));
String nome = json_data.getString("nome");
String cognome = json_data.getString("cognome");
Log.d("JSON",nr+","+nome+","+cognome);
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
       }
   }   
});
thread.start(); 
}

private String readJson() {
      String line = null;
  StringBuilder builder = new StringBuilder();
   HttpClient client = new DefaultHttpClient();
   HttpGet httpGet = new HttpGet("http://192.168.0.100/json.php");
   try {
     HttpResponse response = client.execute(httpGet);
     StatusLine statusLine = response.getStatusLine();
     int statusCode = statusLine.getStatusCode();
     if (statusCode == 200) {
       HttpEntity entity = response.getEntity();
       InputStream content = entity.getContent();
       BufferedReader reader = new BufferedReader(new InputStreamReader(content));
       while ((line = reader.readLine()) != null) {
         builder.append(line);
       }
     } else {
       Log.d("JSON", "Failed to download file");
     }
   } catch (ClientProtocolException e) {
     e.printStackTrace();
   } catch (IOException e) {
     e.printStackTrace();
   }

//Log.d("JSON",line);
   return builder.toString();
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {

// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}

/**
* A placeholder fragment containing a simple view.
*/
public static class PlaceholderFragment extends Fragment {

public PlaceholderFragment() {
}

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_main, container,
false);
return rootView;
}
}

}




Geologi

  E so anche espatriare senza praticamente toccare strada asfaltata