Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
73 views
in Technique[技术] by (71.8m points)

java - How to handle Call<Object> Response as String?

Im in a confusing spot right now. My API returns a Token for Login when posting a new User with UserData. How do I get the response.body() as a String to save it?

It only returns a Post object what I don't actually want. I only use it to create the Post.

 private void createPost(User user) {

        Post post = new Post(user.getName(), user.getGender(), user.getBirthyear(), user.getHeight(),user.getWeight());
        Call<Post> call = jsonmongo.createPost(post);
        // To execute it asynchron
        call.enqueue(new Callback<Post>() {
            @Override
            public void onResponse(Call<Post> call, Response<Post> response) {
                if (!response.isSuccessful()) {
                    Log.e("RESPONSECODE", ""+ response.code());
                    return;
                }                    
                Log.e("RESPONSECODE", ""+ response.code());
            }

            @Override
            public void onFailure(Call<Post> call, Throwable t) {
                Log.e("RESPONSECODE", ""+ t.getMessage());
            }
        });
    }

Get Response.Body and save it to the Database via SQL Adapter ( adapter.addToken(response.body()) )

response.body().toString only returns Object reference ( com.example.Resources.Post@4c8352 )

String S = new Gson().toJson(response.body()) Log.e("JSON", S)

Returns this:

E/JSON: {"age":0,"gender":0,"height":0,"weight":0}

Wanted output: E/JSON: {"token":aslfjkhr9RRRRf283FGr3489pjfGGG34HH89fj}

question from:https://stackoverflow.com/questions/65647353/how-to-handle-callobject-response-as-string

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

let me try... you can use Gson library to create a String json object from the response.

Try it:

new Gson().toJson(response);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...