Problems with api restfull

Asked

Viewed 216 times

3

I have an API Restfull on the local Apache server that returns a list of database users (localhost/api/users).

I’m using the site Jsonlint to validate my JSON. When access via browser i take the result and validate it in Jsonlint, which returns me as valid JSON. An example returned by API:

{
    "usuarios": [
        {
            "id": 167,
            "contrato": 1,
            "cod": "1212",
            "nome": "Marcos Roberto Pavesi",
            "email": "[email protected]",
            "senha": "114fdfefd3d69799f0b6f73ef764d405",
            "ativo": "S",
            "setor": "1",
            "max_add": "",
            "dealer": 0
        },
        {
            "id": 520,
            "contrato": 1,
            "cod": "",
            "nome": "avaliador",
            "email": "[email protected]",
            "senha": "e10adc3949ba59abbe56e057f20f883e",
            "ativo": "S",
            "setor": "2",
            "max_add": "",
            "dealer": 0
        }
    ]
}

However, I am trying to access my application via Java following that explanation and I’m getting the following error:

Exception in thread "main" org.json.Jsonexception:
A Jsonobject text must Begin with '{' at 1 [Character 2 line 1]

at org.json.Jsontokener.syntaxError(Jsontokener.java:433)
at org.json.Jsonobject. (Jsonobject.java:197)
at org.json.Jsonobject. (Jsonobject.java:324)
at com.main.Main.main(Main.java:14)

I am accessing the api with the following code...

public static void main(String[] args) {


        JSONObject obj = new JSONObject("http://localhost:8080/api_carmaix/api/usuarios");
        JSONArray arr = null;
        try {
                arr = obj.getJSONArray("usuarios");
            } catch (JSONException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }




            for (int i = 0; i < arr.length(); i++)
            {            
                System.out.println(arr.getJSONObject(i).getString("id")); 

            }
}

}

  • @Renan edited.. however could you pass me your code? Thank you.

  • I had made a code to test the JSONObject, no more. When you edited the question it became clearer what the problem is.

1 answer

1


Keep in mind that the classes in this package make no requests.
They do the parse from some source (String, Map, ...) and allow you to manipulate the object as a JSON.

Your code launches a JSONException because it is expected a string started by "{" and you are passing a url.

You need to split things: First make the request to get the answer from your API - and here it doesn’t have to be anything complex, you can get the answer as a string. Once you have the answer at hand, you create a JSONObject and passes this string as argument to the constructor.

You can create a method that looks for JSON in a url:

public String getJSON(String url){
    String data = null;

    try {
        HttpURLConnection connection = (HttpURLConnection) new URL(url).openConnection();
        connection.setRequestMethod("GET");
        connection.connect();

        if(connection.getResponseCode() == 200){
            try (BufferedReader buff = new BufferedReader(new InputStreamReader(connection.getInputStream()))){
                String line;
                StringBuilder builder = new StringBuilder();

                while((line = buff.readLine()) != null)
                    builder.append(line);
                data = builder.toString();
            }
        }
    } catch(Exception err){
        // Algum tratamento :)
    }
    return data;
}

Having this method, you can call it by passing the URL that your API returns the JSON with users. And the return, you can pass in the constructor of the JSONObject:

// Resposta da API
String data = getJSON("http://localhost:8080/api_carmaix/api/usuarios");

if (data != null) {
    try {
       // Usando a resposta da API para criar um objeto JSON:
       JSONObject json = new JSONObject(data);

       JSONArray jsonArray = json.getJSONArray("usuarios");
       for (int i = 0; i < jsonArray.length(); i++)
           System.out.println("ID: " + jsonArray.getJSONObject(i).getInt("id"));

    } catch (Exception err) {}
} 

See also that when walking the JSONArray used getInt instead of getString how you are using it. If you try to take the value of "id" as a string JSONException will also be launched containing the message:

Jsonobject["id"] not a string.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.