从URL解析JSON

332nm8kg  于 2023-04-22  发布在  其他
关注(0)|答案(8)|浏览(153)

有没有最简单的方法从URL解析JSON?我用的是Gson,但找不到任何有用的例子。

wvt8vs2t

wvt8vs2t1#

1.首先需要下载URL(文本):

private static String readUrl(String urlString) throws Exception {
    BufferedReader reader = null;
    try {
        URL url = new URL(urlString);
        reader = new BufferedReader(new InputStreamReader(url.openStream()));
        StringBuffer buffer = new StringBuffer();
        int read;
        char[] chars = new char[1024];
        while ((read = reader.read(chars)) != -1)
            buffer.append(chars, 0, read); 

        return buffer.toString();
    } finally {
        if (reader != null)
            reader.close();
    }
}

*然后需要解析(这里有一些选项)。
*GSON(完整示例):

static class Item {
    String title;
    String link;
    String description;
}

static class Page {
    String title;
    String link;
    String description;
    String language;
    List<Item> items;
}

public static void main(String[] args) throws Exception {

    String json = readUrl("http://www.javascriptkit.com/"
                          + "dhtmltutors/javascriptkit.json");

    Gson gson = new Gson();        
    Page page = gson.fromJson(json, Page.class);

    System.out.println(page.title);
    for (Item item : page.items)
        System.out.println("    " + item.title);
}

输出:

javascriptkit.com
    Document Text Resizer
    JavaScript Reference- Keyboard/ Mouse Buttons Events
    Dynamically loading an external JavaScript or CSS file

*尝试json.org的java API:

try {
    JSONObject json = new JSONObject(readUrl("..."));

    String title = (String) json.get("title");
    ...

} catch (JSONException e) {
    e.printStackTrace();
}
wpcxdonn

wpcxdonn2#

GSON有一个构建器,它接受一个Reader对象:fromJson(Reader json, Class<T> classOfT)
这意味着您可以从URL创建一个Reader,然后将其传递给Gson以使用流并进行反序列化。
只有三行相关代码。

import java.io.InputStreamReader;
import java.net.URL;
import java.util.Map;

import com.google.gson.Gson;

public class GsonFetchNetworkJson {

    public static void main(String[] ignored) throws Exception {

        URL url = new URL("https://httpbin.org/get?color=red&shape=oval");
        InputStreamReader reader = new InputStreamReader(url.openStream());
        MyDto dto = new Gson().fromJson(reader, MyDto.class);

        // using the deserialized object
        System.out.println(dto.headers);
        System.out.println(dto.args);
        System.out.println(dto.origin);
        System.out.println(dto.url);
    }
    
    private class MyDto {
        Map<String, String> headers;
        Map<String, String> args;
        String origin;
        String url;
    }
}

如果你碰巧得到一个403错误代码与一个端点,否则工作正常(例如与curl或其他客户端),那么一个可能的原因可能是该端点需要一个User-Agent头,默认情况下Java URLConnection没有设置它。一个简单的修复方法是在文件的顶部添加,例如System.setProperty("http.agent", "Netscape 1.0");

Maven依赖
<!-- https://mvnrepository.com/artifact/com.google.code.gson/gson -->
<dependency>
    <groupId>com.google.code.gson</groupId>
    <artifactId>gson</artifactId>
    <version>2.10.1</version>
</dependency>
Gradle依赖
implementation 'com.google.code.gson:gson:2.10.1'
kmb7vmvb

kmb7vmvb3#

您可以使用org.apache.commons.io.IOUtils进行下载,使用org.json.JSONTokener进行解析:

JSONObject jo = (JSONObject) new JSONTokener(IOUtils.toString(new URL("http://gdata.youtube.com/feeds/api/videos/SIFL9qfmu5U?alt=json"))).nextValue();
System.out.println(jo.getString("version"));
qfe3c7zg

qfe3c7zg4#

这里有一个简单的方法。
首先从url解析JSON-

public String readJSONFeed(String URL) {
    StringBuilder stringBuilder = new StringBuilder();
    HttpClient httpClient = new DefaultHttpClient();
    HttpGet httpGet = new HttpGet(URL);

    try {

        HttpResponse response = httpClient.execute(httpGet);
        StatusLine statusLine = response.getStatusLine();
        int statusCode = statusLine.getStatusCode();

        if (statusCode == 200) {

            HttpEntity entity = response.getEntity();
            InputStream inputStream = entity.getContent();
            BufferedReader reader = new BufferedReader(
                    new InputStreamReader(inputStream));
            String line;
            while ((line = reader.readLine()) != null) {
                stringBuilder.append(line);
            }

            inputStream.close();

        } else {
            Log.d("JSON", "Failed to download file");
        }
    } catch (Exception e) {
        Log.d("readJSONFeed", e.getLocalizedMessage());
    }
    return stringBuilder.toString();
}

然后放置一个任务,然后从JSON中读取所需的值-

private class ReadPlacesFeedTask extends AsyncTask<String, Void, String> {
    protected String doInBackground(String... urls) {

        return readJSONFeed(urls[0]);
    }

    protected void onPostExecute(String result) {

        JSONObject json;
        try {
            json = new JSONObject(result);

        ////CREATE A JSON OBJECT////

        JSONObject data = json.getJSONObject("JSON OBJECT NAME");

        ////GET A STRING////

        String title = data.getString("");

        //Similarly you can get other types of data
        //Replace String to the desired data type like int or boolean etc.

        } catch (JSONException e1) {
            e1.printStackTrace();

        }

        //GETTINGS DATA FROM JSON ARRAY//

        try {

            JSONObject jsonObject = new JSONObject(result);
            JSONArray postalCodesItems = new JSONArray(
                    jsonObject.getString("postalCodes"));

                JSONObject postalCodesItem = postalCodesItems
                        .getJSONObject(1);

        } catch (Exception e) {
            Log.d("ReadPlacesFeedTask", e.getLocalizedMessage());
        }
    }
}

然后你可以像这样放置一个任务-

new ReadPlacesFeedTask()
    .execute("JSON URL");
khbbv19g

khbbv19g5#

public static TargetClassJson downloadPaletteJson(String url) throws IOException {
        if (StringUtils.isBlank(url)) {
            return null;
        }
        String genreJson = IOUtils.toString(new URL(url).openStream());
        return new Gson().fromJson(genreJson, TargetClassJson.class);
    }
xcitsw88

xcitsw886#

import org.apache.commons.httpclient.util.URIUtil;
 import org.apache.commons.io.FileUtils;
 import groovy.json.JsonSlurper;
 import java.io.File;

    tmpDir = "/defineYourTmpDir"
    URL url = new URL("http://yourOwnURL.com/file.json");
    String path = tmpDir + "/tmpRemoteJson" + ".json";
    remoteJsonFile = new File(path);
    remoteJsonFile.deleteOnExit(); 
    FileUtils.copyURLToFile(url, remoteJsonFile);
    String fileTMPPath = remoteJsonFile.getPath();

    def inputTMPFile = new File(fileTMPPath);
    remoteParsedJson = new JsonSlurper().parseText(inputTMPFile.text);
vkc1a9a2

vkc1a9a27#

我使用java1.8和Jackson

ObjectMapper mapper = new ObjectMapper();
Integer      value = mapper.readValue(new URL("your url here"), Integer.class);

Integer.class也可以是一个复杂的类型。只是作为例子使用。

k4emjkb1

k4emjkb18#

一个简单的替代解决方案:

  • 将URL粘贴到json到csv转换器中
  • 在Excel或Open Office中打开CSV文件
  • 使用电子表格工具分析数据

相关问题