在java中如何访问一个json网站获取json中的某个值
在Java中,你可以使用一些库来访问一个JSON网站并获取其中的某个值。以下是使用常见的JSON库来实现的示例代码:
- 使用 org.json 库:
import org.json.JSONObject;
import java.net.URL;
import java.io.BufferedReader;
import java.io.InputStreamReader;
public class JsonExample {
public static void main(String[] args) {
try {
// 创建URL对象并连接到JSON网站
URL url = new URL("http://example.com/api/data.json");
BufferedReader reader = new BufferedReader(new InputStreamReader(url.openStream()));
// 读取JSON数据并解析为JSONObject
StringBuilder jsonBuilder = new StringBuilder();
String line;
while ((line = reader.readLine()) != null) {
jsonBuilder.append(line);
}
reader.close();
JSONObject jsonObject = new JSONObject(jsonBuilder.toString());
// 获取JSON中的某个值
String value = jsonObject.getString("key");
// 打印获取到的值
System.out.println(value);
} catch (Exception e) {
e.printStackTrace();
}
}
}
- 使用 Jackson 库:
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import java.net.URL;
public class JsonExample {
public static void main(String[] args) {
try {
// 创建ObjectMapper对象
ObjectMapper objectMapper = new ObjectMapper();
// 创建URL对象并连接到JSON网站
URL url = new URL("http://example.com/api/data.json");
// 将JSON数据读取为JsonNode对象
JsonNode jsonNode = objectMapper.readTree(url);
// 获取JSON中的某个值
String value = jsonNode.get("key").asText();
// 打印获取到的值
System.out.println(value);
} catch (Exception e) {
e.printStackTrace();
}
}
}
请注意,这只是示例代码,你需要将URL替换为你要访问的JSON网站的实际URL,并将"key"替换为你要获取的JSON值的键
原文地址: https://www.cveoy.top/t/topic/h6mX 著作权归作者所有。请勿转载和采集!