如何解析响应.body okhttp



我在通过okhttp响应解析字符串结果时遇到问题,我想解析这个字符串,但我不知道该怎么做。有人能帮我吗?

我正在使用安卓工作室。

public class MainActivity extends AppCompatActivity {
 
    private TextView mTextViewResult;
 
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
 
        mTextViewResult = findViewById(R.id.text_view_result);
 
        OkHttpClient client = new OkHttpClient();
 
        String url = "https://reqres.in/api/users?page=2";
 
        Request request = new Request.Builder()
                .url(url)
                .build();
 
        client.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                e.printStackTrace();
            }
 
            @Override
            public void onResponse(Call call, Response response) throws IOException {
                if (response.isSuccessful()) {
                    final String myResponse = response.body().string();
 
                    MainActivity.this.runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            mTextViewResult.setText(myResponse);
                        }
                    });
                }
            }
        });
    }
}

块报价[{"attributes}:{>message}:}以下是一些入门资源:\n\n-配置家庭助理\n-可用组件\n-配置疑难解答\n-获取帮助\n\n若要以后看不到此卡弹出窗口,请在configuration.yaml中编辑您的配置并禁用introduction组件{"id":"840e4ec2072144cfa7d53550796dc35d","parent_id":null,"user_id":null},";entity_id":"通知"last_changed":"2019-04-11T22:44:04.942593+00:00"last_updated":"2019-04-11T22:44:04.942593+00:00"状态":"通知"},{"属性":{"方位角":282.29,"仰角":37.79,"友好_名称":"太阳","下一个黎明":"2019-04-15T05:35+00:0","上一个黄昏":"2019 9-04-14T18:24:46+00:00","下一个中午":"2019-04-15T12:0:13+00:00","下一次上升":"2019 9-04-15T05:56:50+00:00"next_setting":"2019-04-14T18:03:50+00:00"}"上下文":{"id":"a8908c263c854345a5183585553319876","parent_id":null,"user_id":null},";entity_id":"sun.sun"last_changed":"2019-04-14T05:57:06.013733+00:00"last_updated":"2019-04-14T15:26:3009359+000:00"状态":"above_horizon"},由挪威气象研究所提供的met.no天气预报;https://api.met.no/weatherapi/weathericon/1.1/?symbol=10;content_type=image/png"friendly_name":"yr符号"}"上下文":{"id":"e2d38361a1704e2a97a78dca780e20&","parent_id":null,"user_id":null},";entity_id":"sensor.yr_symbol"last_changed":"2019-04-14T14:31:0098478+00:00"last_updated":"2019-04-14T14:31:0098478+00:00"状态":"10〃},{"attributes":{"friendly_name":"potenza massima stufa","last_triggered":null},";上下文":{"id":"708bfbddda494f07a11506b5e69e3add","parent_id":null,"user_id":null},";entity_id":"脚本1547400071844"last_changed":"2019-04-11T22:44:27.871225+00:00"last_updated":"2019-04-11T22:44:27.871225+00:00"状态":"off"},{"attributes":{"friendly_name":"potenza minima stufa","last_triggered":null},";上下文":{"id":"9721b6341250436e8050556e44015ebd","parent_id":null,"user_id":null},";entity_id":"脚本1547305398108"last_changed":"2019-04-11T22:44:27.872132+00:00"last_updated":"2019-04-11T22:44:27.872132+00:00"状态":"off"},{"属性":{"设备类别":"连接","友好名称":"远程UI"};上下文":{"id":"4429627581ef481785396af892bb92cc","parent_id":null,"user_id":null},";entity_id":"binary_sensor.remote_ui"last_changed":"2019-04-11T22:44:27.901163+00:00"last_updated":"2019-04-11T22:44:27.901163+00:00"状态":"不可用"},{"attributes":{"access_token":"6304d62742f4b9792101bdb83ee7a7953c1263bc7276e42e6b4f5c6b8a579253","entity_picture":"/api/comerate_proxy/camera.front_window?token=6304d62742f4B979201bdb83 ee7a7953C1263bc726e42e4b4f5c8a579253","supported_features":0},";上下文":{"id":"53ddda3891f24b2b88ecedf43d27186a","parent_id":null,"user_id":null},";entity_id":"camera.front_window"last_changed":"2019-04-11T22:44:27.911773+00:00"last_updated":"2019-04-14T15:22:32.548799+00:00"状态":"空闲"},{"属性":{"auto":true,"entity_id":["script.154740071844","script.154730339808"],"friendly_name":"所有脚本","隐藏":true、"顺序":0};上下文":{"id":"d0230ccfddf4407fab7e784b3539fa3b","parent_id":null,"user_id":

块报价

使用Gson解析器。链接是Gson

现在,关于如何处理字符串的文档在这里

首先,通过您的请求,结果是

{
"page": 2,
"per_page": 3,
"total": 12,
"total_pages": 4,
"data": [
{
"id": 4,
"first_name": "Eve",
"last_name": "Holt",
"avatar": "https://s3.amazonaws.com/uifaces/faces/twitter/marcoramires/128.jpg"
},
{
"id": 5,
"first_name": "Charles",
"last_name": "Morris",
"avatar": "https://s3.amazonaws.com/uifaces/faces/twitter/stephenmoon/128.jpg"
},
{
"id": 6,
"first_name": "Tracey",
"last_name": "Ramos",
"avatar": "https://s3.amazonaws.com/uifaces/faces/twitter/bigmancho/128.jpg"
}
]
}

第二,声明一个类,比如这个

public class ResponseResult {
private int page;
private int per_page;
private int total;
private int total_pages;
private List<DataBean> data;
public int getPage() {
return page;
}
public void setPage(int page) {
this.page = page;
}
public int getPer_page() {
return per_page;
}
public void setPer_page(int per_page) {
this.per_page = per_page;
}
public int getTotal() {
return total;
}
public void setTotal(int total) {
this.total = total;
}
public int getTotal_pages() {
return total_pages;
}
public void setTotal_pages(int total_pages) {
this.total_pages = total_pages;
}
public List<DataBean> getData() {
return data;
}
public void setData(List<DataBean> data) {
this.data = data;
}
public static class DataBean {
private int id;
private String first_name;
private String last_name;
private String avatar;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getFirst_name() {
return first_name;
}
public void setFirst_name(String first_name) {
this.first_name = first_name;
}
public String getLast_name() {
return last_name;
}
public void setLast_name(String last_name) {
this.last_name = last_name;
}
public String getAvatar() {
return avatar;
}
public void setAvatar(String avatar) {
this.avatar = avatar;
}
}
}

然后,在您的改装响应中,尝试使用Gson解析String,如下所示。

Gson gson = new Gson();
ResponseResult responseResult=gson.fromJson(response.body().string(), ResponseResult.class);

现在,您可以通过对象responseResult使用它。

当然,有更简洁的方法来处理这个问题。但是我建议你应该先掌握这个方法。

考虑以下json:

{
"tag": "tg1",
"version": "vr1"
}

创建一个与上述内容相对应的类。

data class TermsResponse(val tag: String, val version: String)

用户retrofit定义您的API:

@GET("/v1/myapi/terms")
Observable<Response<TermsResponse>> getTerms();

使用okhttp进行api调用:

myApi.getTerms()
.subscribeOn(Schedulers.io())
.observeOn(Schedulers.computation())
.subscribe(
{ result -> showResult(result.body() as TermsResponse) },
{ error -> showError(error.message) }
)

这是我请求的代码

public class MainActivity extends AppCompatActivity {   
    private TextView mTextViewResult;    
 
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
 
        mTextViewResult = findViewById(R.id.text_view_result);
 
        OkHttpClient client = new OkHttpClient();
 
        String url = "https://reqres.in/api/users?page=2";
 
        Request request = new Request.Builder()
                .url(url)
                .build();
 
        client.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                e.printStackTrace();
            }
 
            @Override
            public void onResponse(Call call, Response response) throws IOException {
                if (response.isSuccessful()) {
                    final String myResponse = response.body().string();
 
                    MainActivity.this.runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            mTextViewResult.setText(myResponse);
                        }
                    });
                }
            }
        });
    }
}

最简单的方法是使用org.json.*,如下所述:如何在Java 中解析JSON

需要注意的一点是,response.body().string()将只工作一次(如下所述:https://square.github.io/okhttp/4.x/okhttp/okhttp3/-response-body/#the-响应主体只能使用一次),因此您可以利用这一机会将字符串主体保存到技术变量中,然后使用它。

最新更新