首页
学习
活动
专区
工具
TVP
发布
精选内容/技术社群/优惠产品,尽在小程序
立即前往

如何在不知道json键的情况下使用JsonReader从json读取值

在不知道 JSON 键的情况下,可以使用 JsonReader 类从 JSON 中读取值。JsonReader 是一个轻量级的 JSON 解析器,可以逐个读取 JSON 中的元素。

以下是使用 JsonReader 从 JSON 中读取值的步骤:

  1. 创建一个 JsonReader 对象,并将 JSON 字符串作为输入。
  2. 使用 beginObject() 方法开始读取 JSON 对象。
  3. 使用 hasNext() 方法检查是否还有下一个键值对。
  4. 使用 nextName() 方法获取当前键的名称。
  5. 使用 peek() 方法判断当前键对应的值的类型。
  6. 根据值的类型使用相应的方法读取值,例如 nextInt()nextString()nextBoolean() 等。
  7. 使用 endObject() 方法结束读取 JSON 对象。

下面是一个示例代码,演示如何使用 JsonReader 从 JSON 中读取值:

代码语言:txt
复制
import java.io.StringReader;
import java.io.IOException;
import com.google.gson.stream.JsonReader;

public class JsonReaderExample {
    public static void main(String[] args) {
        String json = "{\"name\":\"John\",\"age\":30,\"city\":\"New York\"}";

        try (JsonReader reader = new JsonReader(new StringReader(json))) {
            reader.beginObject();

            while (reader.hasNext()) {
                String key = reader.nextName();

                if (key.equals("name")) {
                    String name = reader.nextString();
                    System.out.println("Name: " + name);
                } else if (key.equals("age")) {
                    int age = reader.nextInt();
                    System.out.println("Age: " + age);
                } else if (key.equals("city")) {
                    String city = reader.nextString();
                    System.out.println("City: " + city);
                } else {
                    reader.skipValue();
                }
            }

            reader.endObject();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

上述代码将输出以下结果:

代码语言:txt
复制
Name: John
Age: 30
City: New York

这个例子假设 JSON 中只包含 "name"、"age" 和 "city" 三个键,并且它们的值分别是字符串、整数和字符串类型。根据实际情况,你可以根据需要读取其他类型的值。

页面内容是否对你有帮助?
有帮助
没帮助

相关·内容

没有搜到相关的沙龙

领券