JSON treatment returned from PHP

Asked

Viewed 234 times

0

I would like to know how to manipulate the data JSON below. If the structure is correct, and if not, how change the structure of it?

{
    "postagens":[
    {
        "URLIMG":"1.jpg",
        "NOME":"Jhonatan",
        "SOBRENOME":"Pereira",
        "ID":"2",
        "IDUSER":"1",
        "POST":"Mais uma postagem de teste"
    },
    {
        "URLIMG":"1.jpg",
        "NOME":"Jhonatan",
        "SOBRENOME":"Pereira",
        "ID":"1",
        "IDUSER":"1",
        "POST":"Fim!"
    }],
    "ups":[
        ["1"],
        ["2"]
    ]
}

The PHP that generates this JSON is:

$id = $_POST['id']; // id do usuário, igual a 1 para teste.
try {
    //conexao com o BD ocultada aqui (variavel $db)
    $contractQuery = $db->prepare("SELECT du.URLIMG, du.NOME, du.SOBRENOME, f.ID, f.IDUSER, f.CURTIDAS, f.NAOCURTIDAS, f.HORA, f.DIA, f.MES, f.ANO, f.POST FROM appfeed f, appdadosuser du WHERE f.IDUSER = du.ID ORDER BY f.ID DESC LIMIT 0 , 30");

    $typesQuery = $db->prepare("SELECT IDPOST FROM appcurtidas WHERE `iduser` = 1 LIMIT 0 , 30");

    $contractQuery->execute(array($id));
    $typesQuery->execute(array($id));

    $result = array();
    $result['postagens'] = $contractQuery->fetchAll(PDO::FETCH_ASSOC);
    $result['ups'] = $typesQuery->fetchAll(PDO::FETCH_NUM);

    echo json_encode($result); //return json
} catch (PDOException $exc) {

}

I know I must use JSONArray and JSONObject, and that Object is {} and Array is [], I just can’t seem to think about the use due to the stretch that differs from the rest of the JSON:

"ups":[
        ["1"],
        ["2"]
    ]
  • Check out these links: http://json.org/json-pt.html and http://developer.android.com/reference/org/json/package-summary.html

  • And according to https://jsonformatter.curiousconcept.com/, this JSON is valid.

  • I will see and return the result tomorrow was worth

2 answers

4

You can follow the following steps 1-create classes pojo 2-add the retrofit lib to your project 3-perform requests using the Rest concept (hence step 2)

1 create pojo classes

The class "pojo" serves to model in java the structure of its json, basically it represents on the android side the data that will be received for json. This class is used by the retrofit to convert the received json to the structure of the passed class (pojo). You can generate these classes (pojo) using the following website: http://pojo.sodhanalibrary.com/ just copy a valid json and it will return you the pojo classes. For your case we have

Java posts.

public class Postagens{

private String POST;

private String URLIMG;

private String ID;

private String SOBRENOME;

private String IDUSER;

private String NOME;

public String getPOST ()
{
    return POST;
}

public void setPOST (String POST)
{
    this.POST = POST;
}

public String getURLIMG ()
{
    return URLIMG;
}

public void setURLIMG (String URLIMG)
{
    this.URLIMG = URLIMG;
}

public String getID ()
{
    return ID;
}

public void setID (String ID)
{
    this.ID = ID;
}

public String getSOBRENOME ()
{
    return SOBRENOME;
}

public void setSOBRENOME (String SOBRENOME)
{
    this.SOBRENOME = SOBRENOME;
}

public String getIDUSER ()
{
    return IDUSER;
}

public void setIDUSER (String IDUSER)
{
    this.IDUSER = IDUSER;
}

public String getNOME ()
{
    return NOME;
}

public void setNOME (String NOME)
{
    this.NOME = NOME;
}

@Override
public String toString()
{
    return "ClassPojo [POST = "+POST+", URLIMG = "+URLIMG+", ID = "+ID+", SOBRENOME = "+SOBRENOME+", IDUSER = "+IDUSER+", NOME = "+NOME+"]";
}}

Mypojo.java

public class MyPojo{

private Postagens[] postagens;

private String[][] ups;

public Postagens[] getPostagens ()
{
    return postagens;
}

public void setPostagens (Postagens[] postagens)
{
    this.postagens = postagens;
}

public String[][] getUps ()
{
    return ups;
}

public void setUps (String[][] ups)
{
    this.ups = ups;
}

@Override
public String toString()
{
    return "ClassPojo [postagens = "+postagens+", ups = "+ups+"]";
}}

2 add retrofit

This lib is responsible for making requests and "abstract" all necessary coding, you can find it here: http://square.github.io/retrofit/ Rest concept : https://en.wikipedia.org/wiki/Representational_state_transfer

3 Requests using Rest

For this step it is necessary that you have read and understood step 2. Below is an example of how to use retrofit.

Interface Retrofit

public interface RetrofitService {
@GET("/postagens/{user_id})
Call<MyPojo> getPostagens(@Path ("user_id")String user);}

In this interface will be added all your requests in will be made use of the retrofit. The next step is where the request will be made for your problem so it is necessary to add the base of the url of the server to which the request will be made, it is important to remove the"/" from the end of the url. Follows the code:

public class Requisicao {
private static Retrofit retrofit;
private static RetrofitService service;
public static MyPojo getPostagens(String user_id){

//adding base url

    retrofit = new Retrofit.Builder()
            .baseUrl("URL_BASE")//exemplo: www.facebook.com

                    //GsonConverterFactory é utilizada para transformar  o //json na classe MyPojo

            .addConverterFactory(GsonConverterFactory.create())
            .build();
    service = retrofit.create(AvososService.class);//utilizando metodo definido na interface

//with this call we have the following url www.baseurl.com/posts/user_id

    Call<MyPojo> postagens= service.getPostagens(user_id);

//checking the return

    postagens.enqueue(new Callback<MyPojo>() {
        MyPojo mPojo;
        @Override
        public void onResponse(Response<MyPojo> response, Retrofit retrofit) {
            if (response.message().equals("OK"))//retorno da requisicao ok 
            {
                mPojo = response.getBody();

            }
        }

        @Override
        public void onFailure(Throwable t) {
            t.printStackTrace();
        }
    });
    return mPojo;
}}

It is necessary to add in the project build.Radle the following dependency that will make the class import Gsonconverterfactory

Compile 'com.squareup.retrofit:converter-gson:2.0.0-beta2'

Done this to perform the requisition just do:

Requisicao.getPostagens(user_id);

0


I was able to solve it in a simpler way, using the org.json library.*

JSON returned from PHP:

{"postagens":
    [{"URLIMG":"1.jpg",
      "NOME":"Jhonatan",
      "SOBRENOME":"Pereira",
      "ID":"2",
      "IDUSER":"1",
      "CURTIDAS":"0",
      "NAOCURTIDAS":"0",
      "HORA":"22:25",
      "DIA":"26",
      "MES":"9",
      "ANO":"2015",
      "POST":"Mais uma postagem de teste"},

     {
          "URLIMG":"1.jpg",
          "NOME":"Jhonatan",
          "SOBRENOME":"Pereira",
          "ID":"1",
          "IDUSER":"1",
          "CURTIDAS":"0",
          "NAOCURTIDAS":"0",
          "HORA":"22:00",
          "DIA":"26",
          "MES":"9",
          "ANO":"2015",
          "POST":"Fim da lista de postagens."
     }],
"ups":[
    {"IDPOST":"1"},
    {"IDPOST":"2"}
]

}

Java code:

//variável JSON é o JSON retornado da Web
String[] postsCurtidos; //Receberá os valores de "ups" do JSON
    try {
        JSONObject json = new JSONObject(JSON);

        //Separa os dois arrays do JSON, "postagens" e "ups"
        JSONArray postagens = json.getJSONArray("postagens");
        JSONArray ups = json.getJSONArray("ups");

        //define o tamanho do vetor usado para armazenar os UPs IDs
        postsCurtidos = new String[ups.length()];

        //captura os dados de "ups"
        for (int indexUp = 0; indexUp < ups.length(); indexUp++){
            JSONObject linesUp = (JSONObject) new JSONTokener(ups.getString(indexUp)).nextValue();
            //preenche o vetor com os ids dos ups do JSON
            postsCurtidos[indexUp] = linesUp.getString("IDPOST");
        }

        //agora captura os dados de "postagens"
        for(int indexPost = 0; indexPost < json.length(); indexPost++) {
            JSONObject lines = (JSONObject) new JSONTokener(postagens.getString(indexPost)).nextValue();

            //lines.getString(nome da chave do JSON);
            String nomeCompleto = lines.getString("NOME")+" "+lines.getString("SOBRENOME");
            usuario.setText(nomeCompleto);

            text.setText(lines.getString("POST"));
            int anoBD = Integer.valueOf(lines.getString("ANO"));
            int mesDB = Integer.parseInt(lines.getString("MES"));
            int diaDB = Integer.parseInt(lines.getString("DIA"));

         }
      }//fim try, seguido de catch

Browser other questions tagged

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