You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Java中如何从JSON对象的prices数组获取price_currency值?

访问JSON中prices数组的price_currency字段的方法

嘿,要访问这个JSON里的price_currency字段其实不难,核心是先把字符串形式的JSON解析成可操作的对象结构,下面给你几种在Java里常用的实现方式(毕竟你提到了String output;变量,应该是Java环境对吧):

方法一:使用org.json基础库

这是Java里比较基础的JSON处理库,不需要定义实体类,直接操作JSON对象即可:

首先确保你的项目引入了org.json依赖,然后按以下步骤操作:

  1. 将字符串output转换为JSONObject
  2. 从JSON对象中取出prices数组
  3. 遍历数组(这里示例取第一个元素,你可以根据实际情况循环处理所有元素)
  4. 从数组元素中获取price_currency字段

代码示例:

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

// 假设output已经存储了你的JSON字符串
String output = "..."; // 你的JSON内容

// 1. 转换为JSONObject
JSONObject jsonObject = new JSONObject(output);

// 2. 获取prices数组
JSONArray pricesArray = jsonObject.getJSONArray("prices");

// 3. 取数组中的第一个价格对象(如果有多个元素可以用循环遍历)
if (pricesArray.length() > 0) {
    JSONObject priceObj = pricesArray.getJSONObject(0);
    // 4. 获取price_currency字段
    String priceCurrency = priceObj.getString("price_currency");
    // 现在priceCurrency就是你要的"USD"啦
    System.out.println(priceCurrency);
}

方法二:使用Gson库(Google出品)

如果你的项目经常处理JSON,Gson的序列化/反序列化会更方便,需要先定义对应的实体类来映射JSON结构:

  1. 定义与JSON结构对应的实体类(只需要定义你需要的字段即可):
import java.util.List;

class Product {
    private List<Price> prices;
    // 可以按需添加其他字段比如deliveries,这里只保留prices用于示例

    // Getter方法
    public List<Price> getPrices() {
        return prices;
    }

    // 内部类Price,对应prices数组里的对象
    static class Price {
        private String price_currency;
        // 按需添加其他字段比如price_retail等

        // Getter方法
        public String getPrice_currency() {
            return price_currency;
        }
    }
}
  1. 使用Gson解析字符串并访问字段:
import com.google.gson.Gson;

// 假设output已经存储了你的JSON字符串
String output = "..."; // 你的JSON内容

Gson gson = new Gson();
// 反序列化为Product对象
Product product = gson.fromJson(output, Product.class);

// 访问第一个price对象的price_currency字段
if (product.getPrices() != null && !product.getPrices().isEmpty()) {
    String priceCurrency = product.getPrices().get(0).getPrice_currency();
    System.out.println(priceCurrency);
}

注意点

  • 如果prices数组可能为空,一定要先判断长度或者是否为空,避免出现IndexOutOfBoundsException
  • 不同的JSON库语法略有差异,但核心逻辑都是解析字符串→获取数组→访问数组元素中的字段

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.28 10:12:25