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

Retrofit2获取WordPress自定义字段及JSON解析问题求助

别担心,获取WordPress自定义字段完全可行!作为刚接触Retrofit2的新手,咱们一步步来拆解,帮你搞定这个问题~

一、先给你吃颗定心丸:需求绝对可行

WordPress本身支持通过REST API暴露自定义字段,只要你在后台做好对应设置(比如默认自定义字段要开启API访问,用ACF这类插件的话要启用API支持),再配合Retrofit2就能轻松拿到你要的数据。

二、针对WordPress+Retrofit2的核心实现步骤

你之前看的JSON问答没适配场景,咱们直接从你的实际需求出发:

1. 先搞懂WordPress返回的JSON结构(关键!)

虽然你没贴完整JSON,但WordPress返回的文章数据里,自定义字段通常在这两个位置:

  • 默认REST API:放在meta字段下
  • ACF插件:放在acf字段下

举个常见的示例结构:

{
  "id": 123,
  "title": {
    "rendered": "我的测试文章"
  },
  "meta": {
    "my_custom_tag": "这是自定义字段内容",
    "article_view_count": 456
  }
}

你得先确认自己实际拿到的JSON里,自定义字段的层级和具体字段名,这是后续代码正确解析的基础。

2. 先搭好Retrofit2的基础环境

在你的Module级build.gradle里添加依赖(选稳定版本就行,也可以用最新版):

implementation 'com.squareup.retrofit2:retrofit:2.9.0'
implementation 'com.squareup.retrofit2:converter-gson:2.9.0'

3. 创建对应的数据模型类(Gson解析用)

根据你拿到的JSON结构,写Java/Kotlin数据类,注意字段要和JSON完全对应,大小写敏感!

Kotlin示例(推荐用协程):

// 文章整体数据类
data class PostResponse(
    val id: Int,
    val title: Title,
    val meta: Meta // 自定义字段所在的层级
)

// 标题的子模型
data class Title(
    val rendered: String
)

// 自定义字段的模型,用@SerializedName映射JSON字段名
data class Meta(
    @SerializedName("my_custom_tag")
    val myCustomTag: String,
    @SerializedName("article_view_count")
    val articleViewCount: Int
)

Java示例:

public class PostResponse {
    private int id;
    private Title title;
    private Meta meta;

    // 记得加Getter和Setter

    public static class Title {
        private String rendered;
        // Getter和Setter
    }

    public static class Meta {
        @SerializedName("my_custom_tag")
        private String myCustomTag;
        @SerializedName("article_view_count")
        private int articleViewCount;
        // Getter和Setter
    }
}

4. 定义Retrofit请求接口

写一个接口来定义请求WordPress API的方法:

interface WordPressApi {
    // 获取单篇文章,{id}是文章ID,也可以改成获取文章列表的接口
    @GET("wp-json/wp/v2/posts/{id}")
    suspend fun getPostById(@Path("id") postId: Int): Response<PostResponse>
}

Java版本用Call代替suspend:

public interface WordPressApi {
    @GET("wp-json/wp/v2/posts/{id}")
    Call<PostResponse> getPostById(@Path("id") int postId);
}

注意:把baseUrl设为你的WordPress站点域名(比如https://你的站点.com/),接口里的路径要和WordPress REST API的路径对应。

5. 初始化Retrofit并发起请求

Kotlin协程方式(更简洁):

// 初始化Retrofit
val retrofit = Retrofit.Builder()
    .baseUrl("https://你的WordPress站点.com/")
    .addConverterFactory(GsonConverterFactory.create())
    .build()

val apiService = retrofit.create(WordPressApi::class.java)

// 在协程里发起请求
CoroutineScope(Dispatchers.IO).launch {
    try {
        val response = apiService.getPostById(123) // 替换成你要获取的文章ID
        if (response.isSuccessful) {
            val post = response.body()
            post?.let {
                // 拿到自定义字段啦!
                val customValue = it.meta.myCustomTag
                Log.d("CustomField", "自定义字段值:$customValue")
            }
        } else {
            Log.e("Error", "请求失败:${response.code()}")
        }
    } catch (e: Exception) {
        Log.e("Error", "请求异常:${e.message}")
    }
}

Java示例:

// 初始化Retrofit
Retrofit retrofit = new Retrofit.Builder()
        .baseUrl("https://你的WordPress站点.com/")
        .addConverterFactory(GsonConverterFactory.create())
        .build();

WordPressApi apiService = retrofit.create(WordPressApi.class);

// 发起异步请求
Call<PostResponse> call = apiService.getPostById(123);
call.enqueue(new Callback<PostResponse>() {
    @Override
    public void onResponse(Call<PostResponse> call, Response<PostResponse> response) {
        if (response.isSuccessful()) {
            PostResponse post = response.body();
            if (post != null) {
                String customValue = post.getMeta().getMyCustomTag();
                Log.d("CustomField", "自定义字段值:" + customValue);
            }
        } else {
            Log.e("Error", "请求失败:" + response.code());
        }
    }

    @Override
    public void onFailure(Call<PostResponse> call, Throwable t) {
        Log.e("Error", "请求异常:" + t.getMessage());
    }
});
三、你之前出错的大概率原因
  1. JSON结构不匹配:数据模型类的字段层级、名称和实际返回的JSON不一致,比如没加@SerializedName映射下划线和驼峰命名,或者自定义字段的层级写错了。
  2. Retrofit配置问题:没加Gson转换器,或者baseUrl设置错误(比如末尾没加斜杠,域名写错)。
  3. WordPress API设置问题:自定义字段没暴露到REST API里。如果是默认自定义字段,需要在主题的functions.php里加这段代码开启:
add_action( 'rest_api_init', function () {
    register_rest_field( 'post', 'my_custom_tag', array(
        'get_callback' => function ( $post ) {
            return get_post_meta( $post['id'], 'my_custom_tag', true );
        },
    ) );
} );

如果用ACF插件,要在ACF设置里开启「REST API支持」。

四、如果还是卡壳

可以把你完整的JSON响应内容,还有之前写的代码(比如数据模型类、Retrofit接口)贴出来,这样能更精准地帮你排查问题~

内容的提问来源于stack exchange,提问作者M ASED AHMED

火山引擎 最新活动