Access a JSON key

Asked

Viewed 566 times

1

I am making a POST request for my Webservice and am getting as a result a Json, I would like to pick a specific field of Json, because the key names are fixed ex: "campo1, campo2,campo3"... and so on. I’m trying to use GSON but I’m unsuccessful.

Example of the return of the 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 take only field 1 and print it instead of all 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);
    }
}

1 answer

1

I don’t understand why json is a size 1 array, so you can use Jsonarray to take the first (and only) object from the array and then take 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();
    }
}

Exit:

Field 1: 3257 | 74327

Field 5: 5

If the server can return a json array larger than 1 it will be necessary to perform a loop by swapping getJSONObject(0) for getJSONObject(i), otherwise all other vector positions will be ignored

  • I tried this way and got no result I did not print anything on the console

  • Error occurred "org.json.Jsonexcepetion: Value [{"campo1":"3257 / 74327", "campo5":"Sidnei"}] of type org.json.Jsonarray cannot be converted to Jsonobject"

  • Sorry, now I realized that there is an array of only 1 object, try with the changes I made in my reply

  • Thank you very much!!

  • You’re welcome! Choose the best answer

Browser other questions tagged

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