如何使用 JsonReader
代码示例:
package org.example;
import com.google.gson.stream.JsonReader;
import org.junit.jupiter.api.Test;
import java.io.IOException;
import java.io.StringReader;
import java.util.Objects;
public class TestJsonReader {
@Test
public void test() throws IOException {
String jsonData = "{\"age\":18, \"height\":180}";
StringReader stringReader = new StringReader(jsonData);
JsonReader jsonReader = new JsonReader(stringReader);
jsonReader.beginObject();
while (jsonReader.hasNext()) {
String name = jsonReader.nextName();
System.out.println("获取到 name 为: " + name);
if (Objects.equals(name, "age")) {
int age = jsonReader.nextInt();
System.out.println("获取到 int 值: " + age);
} else {
System.out.println("跳过");
jsonReader.skipValue();
}
}
jsonReader.endObject();
jsonReader.close();
}
}
执行结果:
获取到 name 为: age
获取到 int 值: 18
获取到 name 为: height
跳过