0

How can I "put" the output generated, which looks to be valid JSON, into an actual JSON object?

According to this answer, gson requires that a class be defined. Surely there's a dynamic way to load or define a class? Or a generic type?

In XML a schema or DTD would be available. Can I dynamically load or find something like that for JSON, using gson?

code:

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??
    }
}

wikipedia 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.

The arbitrary three URL's I'm working with:

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

3

1 Answer 1

1

You can use following

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());
2

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.