You need to enable JavaScript to run this app.
最新活动
大模型
产品
解决方案
定价
生态与合作
支持与服务
开发者
了解我们

Android开发:如何将API返回的JSON解析为单个字符串变量

我来帮你搞定这个问题!在Android里解析OMDB的JSON响应并提取特定字段到String变量,需要注意两个关键点:网络请求不能在主线程,以及正确解析JSON结构。下面是一步步的解决方案:

解析OMDB API返回的JSON到String变量(Android)

第一步:添加网络权限

首先确保你的AndroidManifest.xml里已经添加了网络权限,不然连不上API:

<uses-permission android:name="android.permission.INTERNET" />

第二步:用AsyncTask处理网络请求与JSON解析(基础场景)

Android不允许在主线程执行网络操作,所以我们用AsyncTask来后台处理请求,然后在主线程保存变量或更新UI。这里是嵌入到你的Activity的完整示例代码:

package com.example.project21.stepbystep;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.TextView;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;

public class YourActivity extends AppCompatActivity {

    private String movieTitle; // 用来存储提取到的Title字段

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.your_layout);
        // 比如点击按钮触发请求
        findViewById(R.id.fetch_btn).setOnClickListener(v -> new FetchMovieTask().execute());
    }

    private class FetchMovieTask extends AsyncTask<Void, Void, String> {

        @Override
        protected String doInBackground(Void... voids) {
            HttpURLConnection urlConnection = null;
            BufferedReader reader = null;
            String jsonResponse = null;

            try {
                // 构造API请求URL
                URL url = new URL("http://www.omdbapi.com/?t=Buffy&type=series&plot=short&apikey=8dc1b08d");
                urlConnection = (HttpURLConnection) url.openConnection();
                urlConnection.setRequestMethod("GET");
                urlConnection.connect();

                // 读取响应内容
                reader = new BufferedReader(new InputStreamReader(urlConnection.getInputStream()));
                StringBuilder buffer = new StringBuilder();
                String line;
                while ((line = reader.readLine()) != null) {
                    buffer.append(line).append("\n");
                }
                if (buffer.length() == 0) {
                    return null; // 空响应直接返回
                }
                jsonResponse = buffer.toString();

            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                // 关闭连接和流资源
                if (urlConnection != null) {
                    urlConnection.disconnect();
                }
                if (reader != null) {
                    try {
                        reader.close();
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }
            return jsonResponse;
        }

        @Override
        protected void onPostExecute(String jsonResponse) {
            super.onPostExecute(jsonResponse);
            if (jsonResponse == null) {
                // 处理请求失败的情况
                return;
            }

            try {
                // 解析JSON对象
                JSONObject jsonObject = new JSONObject(jsonResponse);
                // 提取Title字段到String变量
                movieTitle = jsonObject.getString("Title");
                
                // 可以测试输出,比如显示到TextView
                ((TextView) findViewById(R.id.title_text)).setText(movieTitle);
                // 现在movieTitle变量就存储了"Buffy the Vampire Slayer"
            } catch (Exception e) {
                e.printStackTrace();
                // 处理JSON解析错误,比如字段不存在的情况
            }
        }
    }
}

第三步:更现代的实现方式(OkHttp + Coroutines)

如果你的项目用了Kotlin或现代Android开发栈,推荐用OkHttp库配合Coroutines,代码更简洁易维护:

首先在build.gradle添加依赖:

implementation 'com.squareup.okhttp3:okhttp:4.11.0'

然后用Coroutines处理请求与解析:

import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.widget.TextView
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import okhttp3.OkHttpClient
import okhttp3.Request
import org.json.JSONObject

class MainActivity : AppCompatActivity() {
    private lateinit var movieTitle: String

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        findViewById<View>(R.id.fetch_btn).setOnClickListener {
            GlobalScope.launch(Dispatchers.IO) {
                val client = OkHttpClient()
                val request = Request.Builder()
                    .url("http://www.omdbapi.com/?t=Buffy&type=series&plot=short&apikey=8dc1b08d")
                    .build()

                client.newCall(request).execute().use { response ->
                    if (!response.isSuccessful) throw Exception("请求失败")
                    val jsonResponse = response.body?.string() ?: return@launch

                    val jsonObject = JSONObject(jsonResponse)
                    movieTitle = jsonObject.getString("Title")

                    // 回到主线程更新UI
                    withContext(Dispatchers.Main) {
                        findViewById<TextView>(R.id.title_text).text = movieTitle
                    }
                }
            }
        }
    }
}

关键注意事项

  • 异常处理:网络请求可能失败,API也可能返回错误响应(比如Response字段为"False"),建议先检查jsonObject.getString("Response")是否为"True"再提取字段。
  • 空值安全:如果字段可能为null,用optString()代替getString(),避免抛出异常:movieTitle = jsonObject.optString("Title", "默认值")
  • 主线程限制:永远不要在主线程执行网络操作,否则会抛出NetworkOnMainThreadException

内容的提问来源于stack exchange,提问作者Music Backup

火山引擎 最新活动