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

Community
  • 1
  • 1
Thufir
  • 8,216
  • 28
  • 125
  • 273

1 Answers1

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());
Ashish
  • 101
  • 4
  • which API are you using? I'm using gson. I just updated the tag to reflect that, didn't realize there was so much variety in API's on this. – Thufir Feb 23 '16 at 03:12
  • 1
    you can use JSON-java http://www.json.org/ https://github.com/stleary/JSON-java/blob/master/JSONObject.java – Ashish Feb 23 '16 at 03:22