sriram
sriram

Reputation: 9032

Parsing the web page response as Json, in Java

I have a java code:

URL oracle = new URL("https://x.x.x.x.x.x.-001");
System.out.println(oracle.openStream());
BufferedReader in = new BufferedReader(new InputStreamReader(oracle.openStream()));

String inputLine;
while ((inputLine = in.readLine()) != null)
        System.out.println(inputLine);

Which is opening the connection and printing the contents of it. The contents are indeed Json. The output is something like:

{
  "merchantId": "guest",
  "txnId": "guest-1349269250-001",
}

I wish to parse this in json simple jar. I changed the code loop like this:

JSONObject obj = new JSONObject();
while ((inputLine = in.readLine()) != null)
        obj.put("Result",inputLine);

But that doesn't seem to be working. The output I'm getting is:

{"Result":"}"}

Upvotes: 0

Views: 3700

Answers (4)

Flash
Flash

Reputation: 1125

try this link its really helpful if you are going to be logging in or staff like that Java Json simple

import java.io.IOException;
import java.net.URL;

import org.apache.commons.io.IOUtils;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.JSONValue;
import org.json.simple.parser.ParseException;

public class ParseJson1 {

public static void main(String[] args) {
    String url = "http://freemusicarchive.org/api/get/genres.json?api_key=60BLHNQCAOUFPIBZ&limit=2";
    /*
     * {"title":"Free Music Archive - Genres","message":"","errors":[],"total" : "161","total_pages":81,"page":1,"limit":"2",
     * "dataset":
     * [{"genre_id": "1","genre_parent_id":"38","genre_title":"Avant-Garde" ,"genre_handle": "Avant-Garde","genre_color":"#006666"},
     * {"genre_id":"2","genre_parent_id" :null,"genre_title":"International","genre_handle":"International","genre_color":"#CC3300"}]}
     */
    try {
        String genreJson = IOUtils.toString(new URL(url));
        JSONObject genreJsonObject = (JSONObject) JSONValue.parseWithException(genreJson);
        // get the title
        System.out.println(genreJsonObject.get("title"));
        // get the data
        JSONArray genreArray = (JSONArray) genreJsonObject.get("dataset");
        // get the first genre
        JSONObject firstGenre = (JSONObject) genreArray.get(0);
        System.out.println(firstGenre.get("genre_title"));
    } catch (IOException | ParseException e) {
        e.printStackTrace();
    }
}

}

Upvotes: 0

swemon
swemon

Reputation: 5946

You should read whole contents to String variable first and parse it to json. Be careful of ""(double quote). Java uses \" for double quote. Like.

import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;

public class JsonSimpleExample3 {

    public static void main(String args[]) {

        JSONParser parser = new JSONParser();
        //String str = "{\"merchantId\": \"guest\",\"txnId\": \"guest-1349269250-001\",}";

        //intilize an InputStream
        InputStream is = new ByteArrayInputStream("file content".getBytes());

        //read it with BufferedReader and create string
        BufferedReader br = new BufferedReader(new InputStreamReader(is));// Instead of is, you should use oracle.openStream()
        StringBuilder sb = new StringBuilder();

        String line;
        try {
            while ((line = br.readLine()) != null) {
                sb.append(line);
            }
        } catch (IOException e1) {
            e1.printStackTrace();
        } 

        // parse string
        try {
            JSONObject jsonObject = (JSONObject) parser.parse(sb.toString());

            String merchantId = (String) jsonObject.get("merchantId");
            System.out.println(merchantId);
            String txnId = (String) jsonObject.get("txnId");
            System.out.println(txnId);

        } catch (ParseException e) {

            e.printStackTrace();
        }
    }
}

Upvotes: 1

You should use the JSONParser#Parse() method or the JSONValue#parse() method :

URL oracle = new URL("https://x.x.x.x.x.x.-001");
System.out.println(oracle.openStream());
Reader in = new InputStreamReader(oracle.openStream());

Object json = JSONValue.parse(in);

Upvotes: 3

betomontejo
betomontejo

Reputation: 1665

Are you sure you're following the documentation on how to parse a JSON string?

By the looks of it you have to obtain the entire string and call a JSONParse#parse() on it, but your code is filling up a HashMap (JSONObject's parent class) with each of the lines of the JSON. In fact it stores just the last line because you're calling put() with the same "Result" key on every iteration.

Upvotes: 2

Related Questions