M. Ozn
M. Ozn

Reputation: 1220

JSON issue with java program

I'm trying to implement a web service which returns a simple database to read it from a Java application.

My server is running Tomcat 7.

Here is the code which is supposed to create my JSON file :

<%@ page pageEncoding="UTF-8"%>
<%@ page import="java.sql.*" %>
<%@page import="org.json.simple.JSONObject"%> 

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">

<link rel="icon" type="image/png" href="HilevenLogo.png" />

<title>Hileven</title>
</head>
<body>

<%
    Class.forName ("org.postgresql.Driver");

    Connection cnx = DriverManager.getConnection ("jdbc:postgresql://localhost", "user" , "password");

    Statement st = cnx.createStatement();
    ResultSet rs = st.executeQuery("SELECT id, description, libelle, ordre, warning FROM commandes ORDER BY ordre");

    JSONObject obj=new JSONObject();

    while(rs.next()){
        obj.put("id", new Integer(rs.getInt("id")));
        obj.put("description", rs.getString("description"));
        obj.put("libelle", rs.getString("libelle"));
        obj.put("ordre", new Integer(rs.getInt("ordre")));
        obj.put("warning", new Boolean(rs.getBoolean("warning")));

        out.print(obj);
        out.flush();
    }

    rs.close();
    cnx.close();

%>

</body>
</html>

My first question is about the loop. Does a JSON file could have more than one record ? Because my code shows a web page like :

{"ordre":1,"libelle":"Rapport Quotidien","description":"Envoie un rapport journalier de l activité du serveur par mail","warning":false,"id":1}{"ordre":2,"libelle":"Rapport Hebdomadaire","description":"Envoie un rapport hebdomadaire de l activité du serveur par mail","warning":false,"id":2}{"ordre":3,"libelle":"Reboot","description":"Redémarre le serveur","warning":false,"id":3}{"ordre":100,"libelle":"Extinction","description":"Eteint le serveur","warning":true,"id":4}

With 4 {}. Is it possible ?

Then I have my Read class I got in this forum too :

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.net.URL;
import java.nio.charset.Charset;

import org.json.JSONException;
import org.json.JSONObject;

public class JsonReader {

  private static String readAll(Reader rd) throws IOException {
    StringBuilder sb = new StringBuilder();
    int cp;
    while ((cp = rd.read()) != -1) {
      sb.append((char) cp);
    }
    return sb.toString();
  }

  public static JSONObject readJsonFromUrl(String url) throws IOException, JSONException {
    InputStream is = new URL(url).openStream();
    try {
      BufferedReader rd = new BufferedReader(new InputStreamReader(is, Charset.forName("UTF-8")));
      String jsonText = readAll(rd);
      System.out.println(jsonText);
      JSONObject json = new JSONObject(jsonText);
      return json;
    } finally {
      is.close();
    }
  }

  public static void main(String[] args) throws IOException, JSONException {
    JSONObject json = readJsonFromUrl("http://www.hileven.com/admin");
    System.out.println(json.toString());
    System.out.println(json.get("id"));
  }
}

I have this error :

Exception in thread "main" org.json.JSONException: A JSONObject text must begin with '{' at character 6

at the line :

JSONObject json = new JSONObject(jsonText);

So I added a System.out.println(jsonText) just before this line and it returns the entire html code of my page :

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">

<link rel="icon" type="image/png" href="HilevenLogo.png" />

<title>Hileven</title>
</head>
<body>

{"ordre":1,"libelle":"Rapport Quotidien","description":"Envoie un rapport journalier de l activité du serveur par mail","warning":false,"id":1}{"ordre":2,"libelle":"Rapport Hebdomadaire","description":"Envoie un rapport hebdomadaire de l activité du serveur par mail","warning":false,"id":2}{"ordre":3,"libelle":"Reboot","description":"Redémarre le serveur","warning":false,"id":3}{"ordre":100,"libelle":"Extinction","description":"Eteint le serveur","warning":true,"id":4}

</body>
</html>

Is it normal ? I think my JSON web service isn't well configured. Doesn't it has to start the download of a JSON file when we try to go to the URL instead of print all the JSON contents ?

How can I make my JSP returns just the JSON part or even how to make my java program just read the JSON part instead of all the html code ?

Upvotes: 0

Views: 107

Answers (2)

bmargulies
bmargulies

Reputation: 100051

You would find this easier to do with the Jackson library. It will take care of array and object formatting; just put together the whole data structure (a Java array of Java class objects) and call upon Jackson to serialize it.

JSONObject json = new JSONObject(jsonText); 

will not read an array, just a single object. To read [{}, {}, ...] you will need to discover the API that reads arrays of objects.

Upvotes: 1

user2575725
user2575725

Reputation:

Problem lies in the JSON structure, as it has invalid structure. You need to separate each record with a comma , and enclose the entire JSON within [] as you have list of notations.

[{"ordre":1,"libelle":"Rapport Quotidien","description":"Envoie un rapport journalier de l activité du serveur par mail","warning":false,"id":1},{"ordre":2,"libelle":"Rapport Hebdomadaire","description":"Envoie un rapport hebdomadaire de l activité du serveur par mail","warning":false,"id":2},{"ordre":3,"libelle":"Reboot","description":"Redémarre le serveur","warning":false,"id":3},{"ordre":100,"libelle":"Extinction","description":"Eteint le serveur","warning":true,"id":4}]

You need JSON Array along with Object(for each row).

JSONObject obj;
JSONArray list = new JSONArray();

while(rs.next()){
    obj=new JSONObject();
    list.add(obj);
    obj.put("id", new Integer(rs.getInt("id")));
    obj.put("description", rs.getString("description"));
    obj.put("libelle", rs.getString("libelle"));
    obj.put("ordre", new Integer(rs.getInt("ordre")));
    obj.put("warning", new Boolean(rs.getBoolean("warning")));
}
out.print(list);
out.flush();

Also change this line.

JSONObject json = new JSONObject(jsonText);

to

JSONArray json = new JSONArray(jsonText);

Upvotes: 1

Related Questions