Dynamically generate JSON from android form

Asked

Viewed 169 times

2

Context: I have a Cordova app that there are SUS forms with more than 30 fields that is sent to the server through JSON. I’m building a native android APP for the same function;

Problem: Need to map the fields (Edittext, Spinner, Checkbox and Radiobuttons) in JSON objects, in Cordova has the facility of Jquery where I get all the fields of the form through the function $('form') and send to a function that from the type of input maps in JSON ("input.name", "input.value"), already in Java I do not have this facility and for this reason I am mapping field by field and obtaining the "values" of each field of the database because the values that must be in JSON are different from those shown for user sealing.

Goal: there is some library or a way to dynamically pick up all the fields to formulario on android and make a dynamic function that apart from the instanceof response of each field I Mapeie the JSON correctly?

Sample input mapping code for JSON:

/*
 * Geração do JSON apartir do form.
 * A principio é tratado campo por campo pela complexidade em mapear as labels
 * de RadioGroup e Spinner nos valores requeridos pelo sistema de exportação.
 */
private JSONObject formToJSON(View rootView) throws JSONException {
    JSONObject jsonObj = new JSONObject();

    /**
     * Primeira parte
     */
    //Mapeando EditTexts no JSON
    //Nome Paciente
    jsonObj.put(cadNome.getTag().toString(), cadNome.getText().toString());

    //Data Nascimento
    jsonObj.put(cadDataNasc.getTag().toString(), cadDataNasc.getText().toString());

    //Sexo
    String sexo =  rootView.findViewById(cadRadGroupSexo.getCheckedRadioButtonId()).getTag().toString();
    jsonObj.put(cadRadGroupSexo.getTag().toString(), sexo);

    //Tipo Sanguineo
    String tipoSanguineo =  cadTipoSanguineo.getSelectedItem().toString();
    //jsonObj.put(cadRadGroupSexo.getTag().toString(), sexo);
    //TODO obter id do tipo no banco de dados e inserir no JSON

    //Nome da Mãe
    jsonObj.put(cadNomeMae.getTag().toString(), cadNomeMae.getText().toString());

    //Check box desconhece nome pai
    //TODO ver como se obtem o valor do checkbox e inserir de forma correta no JSON

    //Nome pai
    jsonObj.put(cadNomePai.getTag().toString(), cadNomePai.getText().toString());

    /**
     * Segunda parte
     */
    //E-mail
    jsonObj.put(cadEmail.getTag().toString(), cadEmail.getText().toString());

    //Nacionalidade
    String nacionalidade = rootView.findViewById(cadRadGroupNac.getCheckedRadioButtonId()).getTag().toString();
    jsonObj.put(cadRadGroupNac.getTag().toString(), nacionalidade);

    //Pais de nascimento
    String paisNascimento =  cadPaisNasc.getSelectedItem().toString();
    //jsonObj.put(cadPaisNasc.getTag().toString(), );
    //TODO obter id do paisNasc no banco de dados e inserir no JSON

    //Data naturalização
    jsonObj.put(cadDataNatur.getTag().toString(), cadDataNatur.getText().toString());

    //Portaria naturalização
    jsonObj.put(cadPortariaNatu.getTag().toString(), cadPortariaNatu.getText().toString());

    //Data entrada no brasil
    jsonObj.put(cadDataEntrada.getTag().toString(), cadDataEntrada.getText().toString());

    //Estado
    String estado = cadEstado.getSelectedItem().toString();
    //TODO obter id do estado no banco de dados e inserir no JSON

    //Municipio de nascimento
    jsonObj.put(cadMunicipioNasc.getTag().toString(), cadMunicipioNasc.getText().toString());

    //Tipo de documento
    String tipoDoc = cadTipoDoc.getSelectedItem().toString();
    //TODO obter id do Tipo de documento no banco de dados e inserir no JSON

    //Documento
    jsonObj.put(cadDocumento.getTag().toString(), cadDocumento.getText().toString());

    //CNS
    jsonObj.put(cadCns.getTag().toString(),cadCns.getText().toString());

    //Prontuario
    jsonObj.put(cadProntuario.getTag().toString(), cadProntuario.getText().toString());

    //CPF
    jsonObj.put(cadCpf.getTag().toString(), cadCpf.getText().toString());

    //RG
    jsonObj.put(cadRg.getTag().toString(), cadRg.getText().toString());

    //CTPS
    jsonObj.put(cadCtps.getTag().toString(), cadCtps.getText().toString());

    //Raca/Cor
    String racaCor = cadRacaCor.getSelectedItem().toString();
    //TODO obter id do Raca/Cor no banco de dados e inserir no JSON


    return null;
}

Template of a function that would be dynamic that I look for:

public void formToJson(Inputs input){
    if(input instanceof EditText){
        //Executo o mepeamento de EditText
    }
    if(input instanceof Spinner){
        //Executo o mapeamento de Spinner
    }
    //Assim por diante
}
  • Yes, there are libraries that will help you. I recommend the Retrofit . You can create a generic object, if you prefer, for the form and the retrofit will parse the JSON data. Just bring the objects to the fields, which you want to click in Activity.

  • Another option could be GSON. You would create a class that represents your json, with all the required fields. In Activity, you can instantiate this object and set its properties with the values of the components (Edittext etc.). At the end, on a line of code, GSON mounts Json for you. Here a tutorial that may be useful.

  • Thanks for the comments I will test the two tools, the one that gets better I mark as important or if you want to make an answer on this I will mark as answered to that suit me best! Thank you!

No answers

Browser other questions tagged

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