Read JSON file from url Returns null if JSON file is not available - Java JSON

Java examples for JSON:JSON Data

Description

Read JSON file from url Returns null if JSON file is not available

Demo Code


//package com.java2s;
import javax.json.Json;
import javax.json.JsonObject;
import javax.json.JsonReader;

import java.io.File;
import java.io.FileReader;

public class Main {
    /**//  ww w  .  j  ava  2s  . c o m
     * Read JSON file from url
     * <p>
     * Returns null if JSON file is not available
     *
     * @param url
     * @return
     */
    public static JsonObject readJson(String url) {
        JsonObject object = null;
        try {
            String path = new File("").getAbsolutePath() + url;
            JsonReader reader = Json.createReader(new FileReader(path));

            object = reader.readObject();
            reader.close();
        } catch (Exception e) {
            // no json file available
        }

        return object;
    }
}

Related Tutorials