-1

I want to get some values from a JSON using this url:http://api.bitcoincharts.com/v1/markets.json. Im using quick-json to parse it the problem is i don't know how to do it since JSON is very confusing to me in JAVA. I want to get the values that you get here http://api.bitcoincharts.com/v1/markets.json and put them in Hashmap... so i can retrieve them by keys using quick-json for parsing ... can anyone help me tell me how should i proceed using the following code?

import com.json.parsers.JSONParser;
import com.json.parsers.JsonParserFactory;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import sun.org.mozilla.javascript.internal.json.JsonParser;



public class Restfultest { 

    public static float [] lastprice = new float[5000];
    public static float [] amounttraded = new float[5000];
    public static String  allvalue;
    public static int value = 0;
    public static String [] s = new String[4];

    public static void main(String[] args) {

      try {

        URL url = new URL("http://api.bitcoincharts.com/v1/markets.json");
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setRequestMethod("GET");
        conn.setRequestProperty("Accept", "application/json");

        if (conn.getResponseCode() != 200) {
            throw new RuntimeException("Failed : HTTP error code : "
                    + conn.getResponseCode());
        }
                /*
        BufferedReader br = new BufferedReader(new InputStreamReader(
            (conn.getInputStream())));*/

                 JsonParserFactory factory=JsonParserFactory.getInstance();
                 JSONParser parser=factory.newJsonParser();
                 Map jsonData=parser.parse(conn.getInputStream()); /*Gives error because of conn.getInputStream*/


               /*

                  parsing...


                */
        conn.disconnect();

      } catch (MalformedURLException e) {

        e.printStackTrace();

      } catch (IOException e) {

        e.printStackTrace();

      }

    }

the error i get in that line its because the object i put in parse is of type JSONParser how do i use JSON at Java at ALL? this is very confusing... cant find any good examples that show how to connect to an Web API and retrieve some values ...

Really would appreciate some help ... thanks ...

exceltior
  • 103
  • 2
  • 12
  • 2
    What is the exact error you are getting? – Brian Driscoll Jan 16 '14 at 22:58
  • the error is because the object i put in parse is of type JSONParser how do i use JSON at Java at ALL? is very confusing... cant find any good examples that show how to connect to an Web API and retrieve some values ... – exceltior Jan 16 '14 at 23:00
  • @exceltior please copy and paste the exact error message you are receiving, thanks. – Brian Driscoll Jan 16 '14 at 23:03
  • First, ignore Java and learn JSON, at json.org. It's an incredibly simple, easy to learn language that most of the Java tools make far more complicated than need be. – Hot Licks Jan 16 '14 at 23:05
  • There may be bad JSON java tools, but I have successfully used GSON with very little study; it mostly just works, especially for simple cases like what this user is trying to do - IMO, for this level of problem, bogging down in really *understanding* JSON is like taking the time to read and grok all of XML and HTML before you ever lay down your first tag. It's a data transfer format - if you get your data marshaled into an object and can work with it, who cares how it got there? – JVMATL Jan 16 '14 at 23:09
  • @JVMATL - The thing is, no one can ever really understand all of XML or HTML, but you can easily learn all of JSON in 10 minutes. – Hot Licks Jan 16 '14 at 23:11
  • @BrianDriscoll i cannot even compile it since the Jsonparser takes a JSON Erroneous sym type: com.json.parsers.JSONParser.parse at restfultest.Restfultest.main(Restfultest.java:53) – exceltior Jan 16 '14 at 23:21
  • @HotLicks true - JSON is nice and simple to understand - I love using it vs XML whenever I can, but, like .csv files, "simple to understand" doesn't necessarily equate to simple to manually parse and process without having to handle weird edge cases. (FWIW, there are a lot of crummy csv libraries out there, too :) – JVMATL Jan 16 '14 at 23:21
  • One of the advantages of JSON is that many of the "edge cases" have been taken care of by the protocol. And there are so many JSON kits for Java out there I have to believe that ONE of them is pretty good. There's really no need for a JSON kit to run more than about 2000 lines. – Hot Licks Jan 16 '14 at 23:26

3 Answers3

2

Your first problem is unrelated to JSON entirely and simply not understanding Java.

JSONParser.parse() requires an character set name along with the InputStream:

Map<String,String> jsonData=parser.parseJson(conn.getInputStream(), "UTF-8");

After that change, it works fine. However, that's not going to be all that useful.

Looking at the response from the URL you supply, the answer is surprisingly simple: The JSON isn't anything that could be converted to a Map. So what you get is a Map with exactly one entry (root) and the entire JSON response as the value (and mangled to boot).

In short, you're using a really limited, barely documented JSON parser, and from I can find digging through it, it can't parse a JSON response that is an array at the top level.

Edit to add: Here's a complete solution using the Google Gson library to retrieve this data:

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;

public class App
{
   public static void main(String[] args) throws IOException  
    {
        URL url = new URL("http://api.bitcoincharts.com/v1/markets.json");
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setRequestMethod("GET");
        conn.setRequestProperty("Accept", "application/json");

        if (conn.getResponseCode() != 200) {
            throw new RuntimeException("Failed : HTTP error code : "
                    + conn.getResponseCode());
        }

        InputStreamReader isr = new InputStreamReader(conn.getInputStream());
        TypeToken<List<MyJsonClass>> token = new TypeToken<List<MyJsonClass>>(){};
        List<MyJsonClass> list = new Gson().fromJson(isr, token.getType());

        for (MyJsonClass mjc : list)
        {
            System.out.println(mjc.symbol + " : " + mjc.latest_trade);
        }
    } 
}

// No getters / setters for simple example
class MyJsonClass
{

    /*
    {"volume": 8.621800000000, "latest_trade": 1389906326,
        "bid": 11149.760000000000, "high": 10794.930000000000, 
        "currency": "ZAR", "currency_volume": 88097.489637000000, 
        "ask": 9722.590000000000, "close": 10350.000000000000, 
        "avg": 10217.99272042960866640376719, "symbol": "localbtcZAR", 
        "low": 9262.100000000000}
     */

    public double volume;
    public int latest_trade;
    public double bid;
    public double high;
    public String currency;
    public double currency_volume;
    public double ask;
    public double close;
    public double avg;
    public String symbol;
    public double low;
}
Brian Roach
  • 76,169
  • 12
  • 136
  • 161
  • Not java problem at all ... the problem is to find a decent Library for JSON since its such a mess to parse the data into the massive number of fields i have to create to work properly ... – exceltior Jan 17 '14 at 00:08
  • 1
    @exceltior Was feeling generous, see updated answer. – Brian Roach Jan 17 '14 at 00:18
0

The piece you are missing is how to get the data from the InputStream into a String you can parse: see here: Read/convert an InputStream to a String for how to do that - once you know you have a 200 OK response to your request, suck the data from the connection's InputStream into a String and pass it to your parse method.

Community
  • 1
  • 1
JVMATL
  • 2,064
  • 15
  • 25
  • He *has* the `InputStream`; he's passing it to `JsonParser` – Brian Roach Jan 16 '14 at 23:09
  • @BrianRoach I can see he has the input stream, but not every JsonParser takes an input stream, and I can't figure out (from his imports) which one he is using; but the comment in his code says `/*Gives error because of conn.getInputStream*/` -- he gets an error from the input stream he passes to the parse method. So, it seemed likely to me that his JsonParse doesn't take InputStreams - but I can't imagine a JsonParser that won't take a String... – JVMATL Jan 16 '14 at 23:19
  • I'm not sure why you can't figure out what he's using, it's `com.json.parsers.JSONParser` (https://code.google.com/p/quick-json/) which does take an InputStream, hence my comment. – Brian Roach Jan 16 '14 at 23:22
  • He has that other import there, for who knows what. It's unclear what his *actual* problem is since he seems unable to post it. – Brian Roach Jan 16 '14 at 23:27
  • I'm genuinely curious here: How, exactly, did you figure out that he was using quick-json? googling for the package "com.json.parsers.JSONParser" netted me a bunch of mostly useless links - have you used quick-json before? Even after searching their google-code page and wiki, I still don't see a link to the javadoc (or even the name of the package in the examples) So (getting recursive here) I'm not sure why you can't figure out why I can't figure it out. :^) – JVMATL Jan 16 '14 at 23:30
  • Because he said he was :-D (it's in that rambling paragraph, to be fair) – Brian Roach Jan 16 '14 at 23:32
  • doh! Time for some more coffee. Thanks :) – JVMATL Jan 16 '14 at 23:33
  • And actually ... in the end I'm betting you're correct. That code is a mess, I thought I saw a method that just took and input stream but you also have to specify charset. And I've *had* plenty of coffee, so I'm apparently just seeing things :-D – Brian Roach Jan 16 '14 at 23:38
-1

You should take a look into Google's GSON

You can basically make a POJO that holds primiative types and GSON will automatically populate your class it the JSON data.

Take a look at this basic example

quinnjn
  • 623
  • 7
  • 10