Retrofit无法在对象中提取JSON

时间:2017-04-11 23:13:48

标签: android json gson retrofit2

我正在研究如何使用Retrofit停止使用AsyncTask。我有一个名为Network的接口,它发出了我的GET请求,一个ServiceGenerator类创建了我的Retrofit.Builder和我的HTTP拦截器,最后是我的MainActivity(我也实现了这个对象名为Results)的类。

问题在于onResponse中的.enqueue方法(MainActivity):我不知道如何提取JSON并在视图中添加“name”标记。 / p>

这是我的ServiceGenerator课程:

public class ServiceGenerator {
    //URL base do endpoint. Deve sempre terminar com /
    public static final String API_BASE_URL = "https://randomuser.me/";

    public static <S> S createService(Class<S> serviceClass) {
        //Instancia do interceptador das requisições

        HttpLoggingInterceptor loggingInterceptor = new HttpLoggingInterceptor();
        loggingInterceptor.setLevel(HttpLoggingInterceptor.Level.BODY);

        OkHttpClient.Builder httpClient = new OkHttpClient.Builder()
                .readTimeout(5, TimeUnit.SECONDS);

        httpClient.addInterceptor(loggingInterceptor);
        //httpClient.addInterceptor(loggingInterceptor).build();

        //Instância do retrofit
        Retrofit retrofit = new Retrofit.Builder()
                .baseUrl(API_BASE_URL)
                .addConverterFactory(GsonConverterFactory.create(new Gson()))
                .client(httpClient.build())
                .build();

        return retrofit.create(serviceClass);
    }
}

这是我的界面Network

public interface Network {

    @GET("api/")
    Call<Results> randomUser();

}

最后,主要活动:

public class MainActivity2 extends AppCompatActivity {

    private TextView nome;
    private TextView sobrenome;
    private TextView email;
    private TextView endereco;
    private TextView cidade;
    private TextView estado;
    private TextView username;
    private TextView senha;
    private TextView nascimento;
    private TextView telefone;
    private ImageView foto;
    private ProgressDialog load;
    public String gender;
    public Results results;
    public static final String BASE_URL = "https://randomuser.me/";

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

        nome = (TextView) findViewById(R.id.nome);
        sobrenome = (TextView) findViewById(R.id.sobrenome);
        email = (TextView) findViewById(R.id.email);
        endereco = (TextView) findViewById(R.id.endereco);
        cidade = (TextView) findViewById(R.id.cidade);
        estado = (TextView) findViewById(R.id.estado);
        username = (TextView) findViewById(R.id.username);
        senha = (TextView) findViewById(R.id.senha);
        nascimento = (TextView) findViewById(R.id.nascimento);
        telefone = (TextView) findViewById(R.id.telefone);
        foto = (ImageView) findViewById(R.id.foto);

        Network network = ServiceGenerator.createService(Network.class);

         Call<Results> requestUser = network.randomUser();

        requestUser.enqueue(new Callback<Results>() {
            @Override
            public void onResponse(Call<Results> call, Response<Results> response) {
                if (response.isSuccessful()) {

                    ProgressDialog progress = new ProgressDialog(MainActivity2.this);
                    progress.setTitle("sending...");
                    progress.show();
                    Results r = response.body();

                    /*MAYBE I SHOULD PUT SOMETHING HERE:*/

                    if (r != null) {

                        System.out.println();

                       // r.setGender(results.getGender());

                        nome.setText((CharSequence) results.setName(r.getName()));

                        //System.out.println("USER 2: " + response.raw() );

                        //r.setGender(r.getGender());
                        //Results r = new Results();

                        progress.dismiss();

                      //  nome.setText(results.gender.toString());

                        // System.out.println("random user: CARAIO  " + user.random);
                           //nome.setText((CharSequence) r.gender);

                    } else Toast.makeText(MainActivity2.this,"ERROR IN GET JSON",Toast.LENGTH_LONG).show();
                }

                }

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

            }
        });

    }
}

我的Results课程:

public class Results {

    public static String gender;

    public Results(){};

    public static String getGender() {
        return gender;
    }

    public static void setGender(String gender) {
        Results.gender = gender;
    }

    public List<Name> getName() {
        return name;
    }

    public Object setName(List<Name> name) {
        this.name = name;
        return null;
    }

    public List<Location> getLocation() {
        return location;
    }

    public void setLocation(List<Location> location) {
        this.location = location;
    }

    public String getEmail() {
        return email;
    }

    public void setEmail(String email) {
        this.email = email;
    }

    public List<Login> getLogin() {
        return login;
    }

    public void setLogin(List<Login> login) {
        this.login = login;
    }

    public String getPhone() {
        return phone;
    }

    public void setPhone(String phone) {
        this.phone = phone;
    }

    public List<Picture> getPicture() {
        return picture;
    }

    public void setPicture(List<Picture> picture) {
        this.picture = picture;
    }

    public List<Name> name;
    public List<Location> location;
    public String email;
    public List<Login> login;
    public String phone;
    public List<Picture> picture;

}

如果你们能提供帮助,那将非常感激,谢谢。

2 个答案:

答案 0 :(得分:0)

你需要这个: https://github.com/square/retrofit/tree/master/retrofit-converters/jackson 将其添加到gradle并同步。 在创建改造实例时,请调用构建器

.setConverter(new JacksonConverter())

使用jackson进行json反序列化。 使用

更新模型类

@JsonProperty("put name of field here")

然后一切都应该正常工作/

答案 1 :(得分:0)

像这样更改您的网络接口

public interface Network {

    @GET("api/")
    Call<RandomUserServiceResponse> randomUser();

}

在项目中添加此响应模型。它是您的JSON响应的基本响应

 public class RandomUserServiceResponse {

    private List<Result> results = null;
   // private Info info;

    public List<Result> getResults() {
        return results;
    }

    public void setResults(List<Result> results) {
        this.results = results;
    }

}

完成所有这些后的回复

 Call<RandomUserServiceResponse> requestUser = network.randomUser();

        requestUser.enqueue(new Callback<RandomUserServiceResponse>() {
            @Override
            public void onResponse(Call<RandomUserServiceResponse> call, Response<RandomUserServiceResponse> response) {

                if (response.isSuccessful()) {

                    ProgressDialog progress = new ProgressDialog(MainActivity2.this);
                    progress.setTitle("sending...");
                    progress.show();
                    RandomUserServiceResponse r = response.body();



                /* if you want to get NAME tag please */
                Name name = r.getResults().getName();
               /* now you can get Name properties 
               name.getTitle(),name.getFirst(),name.getLast() */




                    if (r != null) {

                        System.out.println();

                       // r.setGender(results.getGender());

                        nome.setText((CharSequence) results.setName(r.getName()));

                        //System.out.println("USER 2: " + response.raw() );


                        //r.setGender(r.getGender());
                        //Results r = new Results();



                        progress.dismiss();

                      //  nome.setText(results.gender.toString());


                        // System.out.println("random user: CARAIO  " + user.random);
                           //nome.setText((CharSequence) r.gender);


                    } else Toast.makeText(MainActivity2.this,"ERROR IN GET JSON",Toast.LENGTH_LONG).show();
                }

                }

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

            }
        });

这是你的结果类

public class Result {

    private String gender;
    private Name name;
    private Location location;
    private String email;
    private Login login;
    private String dob;
    private String registered;
    private String phone;
    private String cell;
    private Id id;
    private Picture picture;
    private String nat;

    public String getGender() {
        return gender;
    }

    public void setGender(String gender) {
        this.gender = gender;
    }

    public Name getName() {
        return name;
    }

    public void setName(Name name) {
        this.name = name;
    }

    public Location getLocation() {
        return location;
    }

    public void setLocation(Location location) {
        this.location = location;
    }

    public String getEmail() {
        return email;
    }

    public void setEmail(String email) {
        this.email = email;
    }

    public Login getLogin() {
        return login;
    }

    public void setLogin(Login login) {
        this.login = login;
    }

    public String getDob() {
        return dob;
    }

    public void setDob(String dob) {
        this.dob = dob;
    }

    public String getRegistered() {
        return registered;
    }

    public void setRegistered(String registered) {
        this.registered = registered;
    }

    public String getPhone() {
        return phone;
    }

    public void setPhone(String phone) {
        this.phone = phone;
    }

    public String getCell() {
        return cell;
    }

    public void setCell(String cell) {
        this.cell = cell;
    }

    public Id getId() {
        return id;
    }

    public void setId(Id id) {
        this.id = id;
    }

    public Picture getPicture() {
        return picture;
    }

    public void setPicture(Picture picture) {
        this.picture = picture;
    }

    public String getNat() {
        return nat;
    }

    public void setNat(String nat) {
        this.nat = nat;
    }

}

这是名称类

public class Name {

    private String title;
    private String first;
    private String last;

    public String getTitle() {
        return title;
    }

    public void setTitle(String title) {
        this.title = title;
    }

    public String getFirst() {
        return first;
    }

    public void setFirst(String first) {
        this.first = first;
    }

    public String getLast() {
        return last;
    }

    public void setLast(String last) {
        this.last = last;
    }

}

和你的图片类

public class Picture {

    private String large;
    private String medium;
    private String thumbnail;

    public String getLarge() {
        return large;
    }

    public void setLarge(String large) {
        this.large = large;
    }

    public String getMedium() {
        return medium;
    }

    public void setMedium(String medium) {
        this.medium = medium;
    }

    public String getThumbnail() {
        return thumbnail;
    }

    public void setThumbnail(String thumbnail) {
        this.thumbnail = thumbnail;
    }

}

这是您的登录类

public class Login {

    private String username;
    private String password;
    private String salt;
    private String md5;
    private String sha1;
    private String sha256;

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    public String getSalt() {
        return salt;
    }

    public void setSalt(String salt) {
        this.salt = salt;
    }

    public String getMd5() {
        return md5;
    }

    public void setMd5(String md5) {
        this.md5 = md5;
    }

    public String getSha1() {
        return sha1;
    }

    public void setSha1(String sha1) {
        this.sha1 = sha1;
    }

    public String getSha256() {
        return sha256;
    }

    public void setSha256(String sha256) {
        this.sha256 = sha256;
    }

}

这里是位置类

public class Location {

    private String street;
    private String city;
    private String state;
    private Integer postcode;

    public String getStreet() {
        return street;
    }

    public void setStreet(String street) {
        this.street = street;
    }

    public String getCity() {
        return city;
    }

    public void setCity(String city) {
        this.city = city;
    }

    public String getState() {
        return state;
    }

    public void setState(String state) {
        this.state = state;
    }

    public Integer getPostcode() {
        return postcode;
    }

    public void setPostcode(Integer postcode) {
        this.postcode = postcode;
    }

}

这是您的Info类(您不需要导入此类)

public class Info {

    private String seed;
    private Integer results;
    private Integer page;
    private String version;

    public String getSeed() {
        return seed;
    }

    public void setSeed(String seed) {
        this.seed = seed;
    }

    public Integer getResults() {
        return results;
    }

    public void setResults(Integer results) {
        this.results = results;
    }

    public Integer getPage() {
        return page;
    }

    public void setPage(Integer page) {
        this.page = page;
    }

    public String getVersion() {
        return version;
    }

    public void setVersion(String version) {
        this.version = version;
    }

}

,最后一个是ID类

public class Id {

    private String name;
    private Object value;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public Object getValue() {
        return value;
    }

    public void setValue(Object value) {
        this.value = value;
    }

}