android 开发 实现对后台返回json数据解析为java对象

发起请求获取json数据

导入依赖

implementation 'com.squareup.okhttp3:okhttp:4.4.1'
implementation 'com.google.code.gson:gson:2.8.6'

发起请求获取数据

Headers.Builder header = new Headers.Builder();
                    header.add("Content-Type", "application/x-www-form-urlencoded");

                    //调用后端接口,设置参数
                    FormBody.Builder params = new FormBody.Builder();
                    params.add("key", key);
                    params.add("version", version);

                    //发送请求,可以使用默认的http,这里使用okhttp请求
                    OkHttpClient client = new OkHttpClient();
                    Request request = new Request.Builder()
                            .url(url)
                            .post(params.build())
                            .build();

                    Response response = client.newCall(request).execute();//执行发送的指令
                    //获取返回过来的参数
                    String responseData = response.body().string();//获取返回过来的json格式结果
                    Log.i("responseData", responseData);


                    //处理responseData
                    JSONObject jsonObject = new JSONObject(responseData.toString());
                    String reason = jsonObject.optString("reason");
                    Log.i("reason", reason);

JOSNObject实现对json数据的解析

// JSONObject 实现解析
                    try {
                        ArrayList<Money> li = new ArrayList<>();
                        JSONObject result = jsonObject.optJSONObject("result");
                        // 创建 JSONArray 对象
                        JSONArray list = result.optJSONArray("list");
                        // 遍历 JSONArray
                        for (int i = 0; i < list.length(); i++) {
                            // 获取数组中的每个 JSONObject
                            JSONObject money = list.getJSONObject(i);
                            // 从 JSONObject 中获取数据
                            String name = money.getString("name");
                            String code = money.getString("code");
                            // 打印收集数据
                            li.add(new Money(name, code));
                        }
                        MyResult myResult = new MyResult(reason, li, jsonObject.optString("error_code"));
                        Log.i("myResult", myResult.toString());
                        Log.i("reason", myResult.getReason());
                        Log.i("list", myResult.listToString());
                        Log.i("error_code", myResult.getError_code());
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }

GSON实现对json数据的解析

// Gson实现解析
                    JSONObject result = jsonObject.optJSONObject("result");
                    String jsonString = result.optString("list");

                    // 使用 Gson 将 JSON 列表转换为 Java 对象列表
                    Gson gson = new Gson();
                    Type personListType = new TypeToken<List<Money>>() {
                    }.getType();
                    List<Money> moneyList = gson.fromJson(jsonString, personListType);

                    // 访问 Java 对象列表的元素
                    for (Money money : moneyList) {
                        System.out.println("Name: " + money.getName());
                        System.out.println("Code: " + money.getCode());
                        System.out.println();
                    }

 完整代码

package com.example.exchagerate;

import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;

import androidx.activity.EdgeToEdge;
import androidx.appcompat.app.AppCompatActivity;


import com.example.exchagerate.bean.Money;
import com.example.exchagerate.bean.MyResult;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.List;

import okhttp3.FormBody;
import okhttp3.Headers;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;


public class MainActivity extends AppCompatActivity implements View.OnClickListener {
    private String url = "http://op.juhe.cn/onebox/exchange/list";
    private String key = "自己申请的key";
    private String version = "2";

    private String need = "result"; //参数名称

    private Button btn;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        EdgeToEdge.enable(this);
        setContentView(R.layout.activity_main);
        btn = findViewById(R.id.btn);
        btn.setOnClickListener(this::onClick);
    }

    @Override
    public void onClick(View v) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    //
                    Headers.Builder header = new Headers.Builder();
                    header.add("Content-Type", "application/x-www-form-urlencoded");

                    //调用后端接口,设置参数
                    FormBody.Builder params = new FormBody.Builder();
                    params.add("key", key);
                    params.add("version", version);

                    //发送请求,可以使用默认的http,这里使用okhttp请求
                    OkHttpClient client = new OkHttpClient();
                    Request request = new Request.Builder()
                            .url(url)
                            .post(params.build())
                            .build();

                    Response response = client.newCall(request).execute();//执行发送的指令
                    //获取返回过来的参数
                    String responseData = response.body().string();//获取返回过来的json格式结果
                    Log.i("responseData", responseData);


                    //处理responseData
                    JSONObject jsonObject = new JSONObject(responseData.toString());
                    String reason = jsonObject.optString("reason");
                    Log.i("reason", reason);


                    // JSONObject 实现解析
                    try {
                        ArrayList<Money> li = new ArrayList<>();
                        JSONObject result = jsonObject.optJSONObject("result");
                        // 创建 JSONArray 对象
                        JSONArray list = result.optJSONArray("list");
                        // 遍历 JSONArray
                        for (int i = 0; i < list.length(); i++) {
                            // 获取数组中的每个 JSONObject
                            JSONObject money = list.getJSONObject(i);
                            // 从 JSONObject 中获取数据
                            String name = money.getString("name");
                            String code = money.getString("code");
                            // 打印收集数据
                            li.add(new Money(name, code));
                        }
                        MyResult myResult = new MyResult(reason, li, jsonObject.optString("error_code"));
                        Log.i("myResult", myResult.toString());
                        Log.i("reason", myResult.getReason());
                        Log.i("list", myResult.listToString());
                        Log.i("error_code", myResult.getError_code());
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }

//                    // Gson实现解析
//                    JSONObject result = jsonObject.optJSONObject("result");
//                    String jsonString = result.optString("list");
//
//                    // 使用 Gson 将 JSON 列表转换为 Java 对象列表
//                    Gson gson = new Gson();
//                    Type personListType = new TypeToken<List<Money>>() {
//                    }.getType();
//                    List<Money> moneyList = gson.fromJson(jsonString, personListType);
//
//                    // 访问 Java 对象列表的元素
//                    for (Money money : moneyList) {
//                        System.out.println("Name: " + money.getName());
//                        System.out.println("Code: " + money.getCode());
//                        System.out.println();
//                    }

                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            Toast.makeText(MainActivity.this, "发送成功", Toast.LENGTH_SHORT).show();
                        }
                    });
                } catch (IOException | JSONException e) {
                    e.printStackTrace();
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            Toast.makeText(MainActivity.this, "网络连接失败", Toast.LENGTH_SHORT).show();
                        }
                    });
                }
            }
        }).start();
    }


}

 bean

package com.example.exchagerate.bean;

public class Money {
    private String name;
    private String code;

    public String getName() {
        return name;
    }

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

    public String getCode() {
        return code;
    }

    public void setCode(String code) {
        this.code = code;
    }

    public Money(String name, String code) {
        this.name = name;
        this.code = code;
    }

    @Override
    public String toString() {
        return "Money{" +
                "name='" + name + '\'' +
                ", code='" + code + '\'' +
                '}';
    }
}
package com.example.exchagerate.bean;

import java.util.List;

public class MyResult {

    String reason;
    List<Money> list;
    String error_code;

    public String getReason() {
        return reason;
    }

    public void setReason(String reason) {
        this.reason = reason;
    }

    public List<Money> getList() {
        return list;
    }

    public String listToString(){
        return list.toString();
    }

    public void setList(List<Money> list) {
        this.list = list;
    }

    public String getError_code() {
        return error_code;
    }

    public void setError_code(String error_code) {
        this.error_code = error_code;
    }

    public MyResult(String reason, List<Money> list, String error_code) {
        this.reason = reason;
        this.list = list;
        this.error_code = error_code;
    }

    @Override
    public String toString() {
        return "MyResult{" +
                "reason='" + reason + '\'' +
                ", list=" + list +
                ", error_code='" + error_code + '\'' +
                '}';
    }
}

xml

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/main"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Hello World!"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <Button
        android:id="@+id/btn"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="按钮"/>

</androidx.constraintlayout.widget.ConstraintLayout>

manifests.xml 

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools">

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

    <application
        android:allowBackup="true"
        android:dataExtractionRules="@xml/data_extraction_rules"
        android:fullBackupContent="@xml/backup_rules"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/Theme.ExchageRate"
        tools:targetApi="31"
        android:usesCleartextTraffic="true">
        <activity
            android:name=".MainActivity"
            android:exported="true">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>

  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值