-1

i'm doing an http call using the new retrofit 2.0, and getting a callback, i want to use gson 2.0 library to parse that json obj and to be able to do

jsonData.sector[2].sectorOne

this is my callback:

retrofitApi.Factory.getInstance().getCallData().enqueue(new Callback<ResponseBody>() {
            @Override
            public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {

                try {

                } catch (IOException e) {
                    e.printStackTrace();
                }

            }

            @Override
            public void onFailure(Call<ResponseBody> call, Throwable t) {
                Log.d("myLogs", "failed to Retrive Data");
                Log.d("myLogs", "becouse: "+t);
                largeTextVar.setText("failed: " + t);
            }
        });

this is how my callback will look like

{
  "data": {
    "sector": [
      [
        {
          "scanned": false,
          "sectorOne": "",
          "sectorTwo": "",
          "sectorThree": ""
        },
        {
          "scanned": false,
          "sectorOne": "",
          "sectorTwo": "",
          "sectorThree": ""
        }
      ]
    ]
  },
  "curserLocation": {
    "elevation": 30,
    "horizontal": 105
  }
}

i'm using :

compile 'com.squareup.retrofit2:retrofit:2.0.1'
compile 'com.squareup.retrofit2:converter-gson:2.0.1' 

i looked everywhere on how to do this, but i couldn't find a simple solution for this, what is the simplest, easiest way to achieve this ?

Yasin Kaçmaz
  • 6,573
  • 5
  • 40
  • 58
Chief Madog
  • 1,738
  • 4
  • 28
  • 55
  • Retrofit with the Gson converter doesn't give you JSON back, it gives you a Java object, so there is no need to use a JSON path like you've asked – OneCricketeer May 08 '16 at 09:41
  • how do you parse that object ? (let's say in my example) @cricket_007 – Chief Madog May 08 '16 at 10:27
  • @cricket_007 ? do you know how to parse the response ? it's something like response.body.string ? something like that ? – Chief Madog May 08 '16 at 13:50
  • You shouldn't need to turn anything into a string. I don't know how you set up retrofit to handle things, but perhaps this will help https://guides.codepath.com/android/Consuming-APIs-with-Retrofit – OneCricketeer May 08 '16 at 14:33
  • yea i'll look into it, i just wanted to acess one of the variables like do response.body.string[2].. etc... – Chief Madog May 08 '16 at 14:55
  • That syntax isn't correct unless you only want the third character of the response... You have to use Gson to convert the string to a JSON object, from which you can obtain the information. However, since you are using Retrofit to obtain your data, you shouldn't need to do that (as explained below, you have a POJO) – OneCricketeer May 08 '16 at 14:58

1 Answers1

0

Okey i will explain how to convert JSON response to POJO :

First of all you must create a POJO class in : JSON Schema 2 POJO

  1. Paste your example JSON response
  2. Select Source Type : JSON
  3. annotation style : Gson

It will generate a POJO class for you.

Then in your onResponse method :

        @Override
        public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
            if(response.code()==200){
            Gson gson = new GsonBuilder().create();
                YourPOJOClass yourpojo=new YourPOJOClass ();
                try {
                    yourpojo= gson.fromJson(response.body().toString(),YourPOJOClass.class); 
                } catch (IOException e) {
                    // handle failure to read error
                    Log.v("gson error","error when gson process");  
                }
        }

Dont forget to add compile 'com.google.code.gson:gson:2.4'

Another way to do this : create a pojo class like in above.

In your API :

@POST("endpoint")
public Call<YourPOJOClass> exampleRequest();

When calling this :

    OkHttpClient okClient = new OkHttpClient.Builder().connectTimeout(10, TimeUnit.SECONDS).build();

    Gson gson = new GsonBuilder()
            .setDateFormat("yyyy-MM-dd'T'HH:mm:ssZ")
            .create();

    Retrofit client = new Retrofit.Builder()
            .baseUrl(baseUrl)
            .addConverterFactory(GsonConverterFactory.create(gson))
            .client(okClient)
            .build();

    YourApiClass service = client.create(YourApiClass.class);

    Call<YourPOJOClass> call=service.exampleRequest();
    call.enqueue(new Callback<YourPOJOClass>() {
        @Override
        public void onResponse(Call<YourPOJOClass> call, Response<YourPOJOClass> response) {
            //already Gson convertor factory converted your response body to pojo
            response.body().getCurserLocation();
        }

        @Override
        public void onFailure(Call<YourPOJOClass> call, Throwable t) {

        }
    });
Yasin Kaçmaz
  • 6,573
  • 5
  • 40
  • 58
  • is there a way you know to acess directly the vars on the response i get from the function ? – Chief Madog May 08 '16 at 13:05
  • no i dont know , i am using pojo classes to get variables. The proper way i know . – Yasin Kaçmaz May 08 '16 at 14:03
  • jsonschema2pojo creates 4 files in the zip folder, in your example you used, YourPOJOClass yourpojo=new YourPOJOClass (), which class from POJO did you mean ? can you exaplain the answer a little bit more ? – Chief Madog May 08 '16 at 14:14
  • 1
    look this photo , look blue lines in photo . Type your classname its just example you can give it a specific name : http://hizliresim.com/RkW8lR .If it generates multi classes add all classes to your project. – Yasin Kaçmaz May 08 '16 at 15:00