Accessing a JSON key

0

I'm doing a POST request to my Webservice and I'm getting a Json as a result, I'd like to get a specific field from Json because the key names are fixed eg: "field1, field2, field3" ... and so on against. I'm trying to use GSON but I'm unsuccessful.

Example return request:

03-02 11:14:03.069 10754-10754/com.example.romeu.myapplication I/System.out: Resultado da Pesquisa: [{"campo1":"3257 | 74327","campo2":"Sidnei","campo3":"sidnei01","campo4":null,"campo5":5,"campo6":null,"campo7":7,"campo8":"74327","campo9":"56c07af798f309dbd75822a849ce47b6","campo10":"2012-02-08T11:00:06"}]

I would like to just get field1 and print it instead of the entire JSON.

My classes: HttpRequest:

package com.example.romeu.myapplication;

/**
 * Created by romeu on 02/03/18.
 */

import android.content.Context;
import org.json.JSONObject;
import java.io.DataOutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Scanner;

public class HttpRequest {

    protected Context context;
    protected String url;
    protected String result = "";
    protected String query = "";

    public HttpRequest(Context context, String url, String query)
    {
        super();
        this.context = context;
        this.url = url;
        this.query = query;
    }

    public String buscarSql() {

        try
        {
            URL requestURL = new URL(url);

            // Instância de HttpURLConnection responsável por acessar a rede
            HttpURLConnection connection = (HttpURLConnection) requestURL.openConnection();
            connection.setDoOutput(true);
            connection.setDoInput(true);
            connection.setInstanceFollowRedirects(false);

            // Requisição via POST
            connection.setRequestMethod("POST");
            connection.setRequestProperty("Content-type", "application/json");
            connection.setRequestProperty("Accept", "application/json");

            //Criando o JSON Object
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("select", query);

            // DataOutputStream responsavel por receber a resposta do servidor
            DataOutputStream wr = new DataOutputStream(connection.getOutputStream());
            wr.writeBytes(jsonObject.toString());
            wr.flush();
            wr.close();

            String response = "";
            Scanner inStream = new Scanner(connection.getInputStream());

            while (inStream.hasNextLine())
            {
                response += (inStream.nextLine());
            }

            result = response;
            inStream.close();
            connection.disconnect();
        }
        catch (Exception e) {}
        return result;
    }
}

QueryTask

public class QueryTask extends AsyncTask<String, Integer, Long> {

    String result = "";
    Context context;
    HttpRequest mHttpRequest;

    public QueryTask(Context context, String query)
    {
        super();
        this.context = context;
        mHttpRequest = new HttpRequest(context, "https://services-dev.redetendencia.com.br/api-rest/helper-qa/select", query);
    }

    @Override
    protected Long doInBackground(String... params)
    {
        result = mHttpRequest.buscarSql();
        return null;
    }

    @Override
    protected void onPostExecute(Long aLong)
    {
        super.onPostExecute(aLong);
        ((Interface) context).onQueryTaskExecute(result);
    }

    public interface Interface {
        void onQueryTaskExecute(String result);
    }

}

Main:

public class MainActivity extends AppCompatActivity implements QueryTask.Interface{

    Button consultar_btn;

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

        consultar_btn = (Button) findViewById(R.id.consultar);

        consultar_btn.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                new QueryTask(MainActivity
                        .this, "select id || ' | ' ||senha_terminal,nome,login_web,null,5,null n2,7,senha_terminal,senha_web,data_inclusao from usuario where id in (3257) order by id desc").execute();

            }

        });
    }

    @Override
    public void onQueryTaskExecute(String result) {
        System.out.println("Resultado da Pesquisa: "+ result);
    }
}
    
asked by anonymous 02.03.2018 / 16:21

1 answer

0

I do not understand why json is an array of size 1, so you can use JSONArray to get the first (and only) object of the array and then get the properties you want from the object, like this:

@Override
public void onQueryTaskExecute(String result) {
    try{
        JSONArray jsonArray = new JSONArray(result);
        JSONObject jsonObject = jsonArray.getJSONObject(0); // Pegando o primeiro e único 
                                                            // objeto json
        String campo1 = jsonObject.getString("campo1");
        int campo5 = jsonObject.getInt("campo5");

        System.out.println("Campo 1: "+ campo1 + "\nCampo 5: "+campo5);
    }catch(JSONException e){
        e.printStackTrace();
    }
}

Output:

  

Field 1: 3257 | 74327

     

Field 5: 5

If the server can return an array of json's larger than 1, it will be necessary to loop through getJSONObject(0) and getJSONObject(i) , otherwise all other vector positions will be ignored

    
03.03.2018 / 14:29