Android Retrofit Post Json Object

Привет, я новичок в использовании Retrofit, и я застрял из-за публикации json на сервере. Изначально у меня были только параметры полей, в которых не было arrayylist. Но теперь у меня есть целый объект json, который содержит строку, логическое значение и список массивов. Итак, я создал класс pojo, сериализовав его. Структура класса pojo приведена ниже.

    public class SeekerProfileModel implements Serializable {

        @SerializedName("_id")
        private String _id=null;
        @SerializedName("full_name")
        private String fullName=null;
        @SerializedName("phone")
        private String phone=null;
        @SerializedName("email")
        private String email=null;
        @SerializedName("native_address")
        private String nativeAddress=null;
        @SerializedName("fresher")
        private Boolean isFresher=null;
        @SerializedName("skills")
        private String skills=null;
        @SerializedName("resume_uri")
        private String resumeUri=null;
        @SerializedName("educational_details")
        private ArrayList<EducationalInfoModel>educationalList=null;

        public SeekerProfileModel(String _id,String fullName,String phone,String email,String nativeaddress,Boolean fresher,String skills,String resumeUri,ArrayList<EducationalInfoModel>educationalInfoList)
        {
            this._id=_id;
            this.fullName=fullName;
            this.phone=phone;
            this.email=email;
            this.nativeAddress=nativeaddress;
            this.isFresher=fresher;
            this.skills=skills;
            this.resumeUri=resumeUri;
            this.educationalList=educationalInfoList;
        }

        public ArrayList<EducationalInfoModel> getEducationalList() {
            return educationalList;
        }

        public void setEducationalList(ArrayList<EducationalInfoModel> educationalList) {
            this.educationalList = educationalList;
        }

        public String get_id() {
            return _id;
        }

        public void set_id(String _id) {
            this._id = _id;
        }

        public String getFullName() {
            return fullName;
        }

        public void setFullName(String fullName) {
            this.fullName = fullName;
        }

        public String getPhone() {
            return phone;
        }

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

        public String getEmail() {
            return email;
        }

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

        public String getNativeAddress() {
            return nativeAddress;
        }

        public void setNativeAddress(String nativeAddress) {
            this.nativeAddress = nativeAddress;
        }

        public Boolean getFresher() {
            return isFresher;
        }

        public void setFresher(Boolean fresher) {
            isFresher = fresher;
        }

        public String getSkills() {
            return skills;
        }

        public void setSkills(String skills) {
            this.skills = skills;
        }

        public String getResumeUri() {
            return resumeUri;
        }

        public void setResumeUri(String resumeUri) {
            this.resumeUri = resumeUri;
        }
    }

А это 2-е pojo arraylist

    public class EducationalInfoModel implements Serializable {
    @SerializedName("_id")
    private String _id=null;
    @SerializedName("profile_id")
    private String profileId=null;
    @SerializedName("grade")
    private String grade=null;
    @SerializedName("board")
    private String board=null;
    @SerializedName("percentage")
    private String percentage=null;


    public EducationalInfoModel(String _id,String profileId,String grade,String board,String percentage)
    {
        this._id=_id;
        this.profileId=profileId;
        this.grade=grade;
        this.board=board;
        this.percentage=percentage;
    }

    public String get_id() {
        return _id;
    }

    public void set_id(String _id) {
        this._id = _id;
    }

    public String getProfileId() {
        return profileId;
    }

    public void setProfileId(String profileId) {
        this.profileId = profileId;
    }

    public String getGrade() {
        return grade;
    }

    public void setGrade(String grade) {
        this.grade = grade;
    }

    public String getBoard() {
        return board;
    }

    public void setBoard(String board) {
        this.board = board;
    }

    public String getPercentage() {
        return percentage;
    }

    public void setPercentage(String percentage) {
        this.percentage = percentage;
    }
}

А вот и мой RetrofitApiInterface.

     @POST("/synkku/operations.php")
void createNewSeekerProfile( @Query("module") String module,
                         @Query("action") String action,
    @Body SeekerProfileModel body, Callback<SeekerProfileModel> callback);

И, наконец, вспомогательный класс Retrofit

public void addNewSeekerProfile(SeekerProfileModel seekerProfileModel) {
        //Here we will handle the http request to insert user to mysql db
        //Creating a RestAdapter
        RestAdapter adapter = new RestAdapter.Builder()
                .setEndpoint(Allconstants.MAIN_URL) //Setting the Root URL
                .build(); //Finally building the adapter
        //Creating object for our interface
        RetroApiInterface api = adapter.create(RetroApiInterface.class);

        //Defining the method insertuser of our interface
        api.createNewSeekerProfile(
                seekerProfileModel,
                new Callback<SeekerProfileModel>() {
                    @Override
                    public void success(SeekerProfileModel seekerProfileModel, Response response) {

                        //On success we will read the server's output using bufferedreader
                        //Creating a bufferedreader object
                        BufferedReader reader = null;

                        //An string to store output from the server
                        String output = "";

                        try {
                            //Initializing buffered reader
                            reader = new BufferedReader(new InputStreamReader(response.getBody().in()));
                            //Reading the output in the string
                            output = reader.readLine();
                            System.out.println("####data coming as success"+response);

                            Toast.makeText(mContext,"data"+output,Toast.LENGTH_LONG).show();
                        } catch (IOException e) {
                            e.printStackTrace();
                            System.out.println("###coming exception");
                        }
                    }

                    @Override
                    public void failure(RetrofitError error) {

                    }
                }
        );
    }

Теперь проблема в том, что данные не публикуются. Любая помощь будет очень признательна.


person md gouse    schedule 05.11.2016    source источник


Ответы (2)


используйте это вместо вашего интерфейса ....

public interface RetroApiInterface {
    @POST("synkku/operations.php")   //removed backslash from url 
    void createNewSeekerProfile(
            @Body SeekerProfileModel body, Callback<SeekerProfileModel> callback);
}

и добавьте эти .addConverterFactory(GsonConverterFactory.create()) строки в свой RestAdapter .... как показано ниже ....

RestAdapter adapter = new RestAdapter.Builder()
                .addConverterFactory(GsonConverterFactory.create()) //these line is convert your POJO into JSON and Vice Versa 
                .setEndpoint(Allconstants.MAIN_URL) //Setting the Root URL
                .build();  

Примечание. - Всегда старайтесь начинать публикацию или получение URL-адреса с обратной косой чертой и ставить обратную косую черту в конце вашего исходного URL-адреса, например (например, www.XXXx.XXXX /).

РЕДАКТИРОВАТЬ: - добавьте эти зависимости в свою оценку ....

добавить

compile 'com.squareup.retrofit2:converter-gson:2.0.0'
compile 'com.google.code.gson:gson:2.7' //this is same as Ravi told 

Приведенный выше пример для модернизации 2.0 и выше либерализует ....

Для модернизации 1.9 ваш URL-адрес в порядке, а RestAdapter также хорош

проверьте свой onFaliure() метод и опубликуйте здесь, если есть какие-либо исключения .........

person sushildlh    schedule 05.11.2016
comment
Я предполагаю, что он использует дооснащение 1.9. - person Ravi Gadipudi; 05.11.2016
comment
Я также использую строки запроса вместе с телом @POST (/synkku/operations.php) void createNewSeekerProfile (@Query (module) String module, @Query (action) String action, @Body SeekerProfileModel body, Callback ‹SeekerProfileModel› callback); - person md gouse; 05.11.2016
comment
@mdgouse Что вы используете для модернизации 1.9 или до версии 2.0 (см. выше)? - person sushildlh; 05.11.2016
comment
невозможно импортировать GsonconverterFactory - person md gouse; 05.11.2016
comment
я использую дооснащение 1.9 - person md gouse; 05.11.2016
comment
добавьте это в группу компиляции зависимостей gradle: 'com.google.code.gson', имя: 'gson', версия: '2.8.0' - person Ravi Gadipudi; 05.11.2016
comment
@mdgouse, вы получаете какую-либо ошибку при неудачной модернизации? - person sushildlh; 05.11.2016
comment
его приближающийся успех, потому что здесь проблема с json в php..if ($ action == post_new_user_profile) {$ data = json_decode (file_get_contents ('php: // input'), true); $ fullname = $ _ POST ['полное_имя']; $ phone = $ _ POST ['contact_phone']; $ email = $ _ POST ['contact_email']; $ nativeaddress = $ _ POST ['полный_адрес']; $ fresher = $ _ POST ['свежее']; $ skills = $ _ POST ['навыки']; $ resumeUri = $ _ POST ['resume_uri']; $ educationDetailsList = $ _ POST ['education_details']; $ obj = json_decode ($ educationDetailsList, истина); createNewUserProfile ($ fullname, $ phone, $ email, $ nativeaddress, $ fresher, $ Skills, $ resumeUri);} - person md gouse; 05.11.2016
comment
он попадает на сервер и вставляет нулевые значения в таблицу - person md gouse; 05.11.2016
comment
Вы проверяли свой URL с POSTMAN. он дает вам успех или неудачу, и вы получаете то, в чем реальная проблема (фронтенд или бэкхенд). - person sushildlh; 05.11.2016

Наконец, проблема была решена. Почтовый запрос с использованием модификации 1.9 с вышеупомянутым кодом работал нормально, просто я пропустил другую строку @query вместе с телом в интерфейсе модификации, и проблема заключалась в json-кодировке php, которую я решил, используя следующие строка кода $ data = json_decode (file_get_contents ('php: // input'), true); $ fullname = $ data ['полное_имя'];

Спасибо всем, кто потратил время на то, чтобы помочь мне с этой проблемой.

person md gouse    schedule 05.11.2016