gpt4 book ai didi

java - 使用 gson 从 URL 动态加载 JSON 元数据

转载 作者:行者123 更新时间:2023-12-01 10:21:34 27 4
gpt4 key购买 nike

如何将生成的输出(看起来是有效的 JSON)“放入”实际的 JSON 对象中?

根据this answer , gson 要求定义一个类。当然有加载或定义类的动态方法吗?还是泛型?

在 XML 中,架构或 DTD 是可用的。我可以使用 gson 动态加载或查找类似 JSON 的内容吗?

代码:

package net.bounceme.noagenda;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import static java.lang.System.out;

public class NoAgenda {

public static void main(String[] args) throws MalformedURLException, IOException {
List<URL> urls = new ArrayList<>();
new NoAgenda().iterateURLs(urls);
}

private void iterateURLs(List<URL> urls) throws MalformedURLException, IOException {
urls.add(new URL("https://www.flickr.com/photos/"));
urls.add(new URL("http://www.javascriptkit.com/dhtmltutors/javascriptkit.json"));
urls.add(new URL("http://api.wunderground.com/api/54f05b23fd8fd4b0/geolookup/conditions/forecast/q/US/CO/Denver.json"));
for (URL url : urls) {
connect(url);
}
}

private void connect(URL url) throws IOException {
out.println(url);
String line = null;
StringBuilder sb = new StringBuilder();
BufferedReader in = new BufferedReader(
new InputStreamReader(url.openStream()));
while ((line = in.readLine()) != null) {
sb.append(line + "\n");
}
in.close();
out.println(sb);

// HOW DO I TURN THIS INTO AN ACTUAL JSON??
}
}

维基百科says :

Schema and metadata

JSON Schema

JSON Schema[20] specifies a JSON-based format to define the structure of JSON data for validation, documentation, and interaction control. A JSON Schema provides a contract for the JSON data required by a given application, and how that data can be modified.

我正在使用的任意三个 URL:

https://www.flickr.com/photos/

http://www.javascriptkit.com/dhtmltutors/javascriptkit.json

http://api.wunderground.com/api/54f05b23fd8fd4b0/geolookup/conditions/forecast/q/US/CO/Denver.json

最佳答案

您可以使用以下内容

StringBuilder sb = new StringBuilder();

String line;
br = new BufferedReader(new InputStreamReader(is));
while ((line = br.readLine()) != null) {
sb.append(line);
}
JSONObject json = new JSONObject(sb.toString());

关于java - 使用 gson 从 URL 动态加载 JSON 元数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35567921/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com