JSON handling returned from PHP

0

I would like to know how to manipulate data from JSON below. If the structure is correct, and if not, how do I 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 should use JSONArray and JSONObject , and that Object is {} and Array is [] , I just can not think of usage because of the stretch that differs from the rest of JSON :

"ups":[
        ["1"],
        ["2"]
    ]
    
asked by anonymous 04.11.2015 / 01:47

2 answers

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
    
07.11.2015 / 02:44
4

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

1 create pojo classes

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

Posts.java

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 "abstracting" all required coding, you can find it here: link concept rest: link

3 Requests using rest

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

Retrofit Interface

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 url base of the server to which the request will be made, it is important to remove the "/" from the end of the url. Here is 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 for 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 build.gradle of the project the following dependency that will import the class GsonConverterFactory

  

compile 'com.squareup.retrofit: convert-gson: 2.0.0-beta2'

This is done to make the request:

Requisicao.getPostagens(user_id);
    
04.11.2015 / 03:32