Saurabh
Saurabh

Reputation: 35

How to create simple web service that takes input as JSONObject in java

Hello I am new to web services.

I am able to create simple web service which accept input string and return another string using eclipse.

But when it comes to JSONObject i am facing problems,while invoking web service

public class HelloWorld {
private int rowNumber;

public byte[] readJSON(JSONObject jsonObject ) throws Exception
{
    rowNumber=0;
    File excelFile = new File("Test2.xlsx");
    OutputStream outStream = new FileOutputStream(excelFile);
    XSSFWorkbook workbook = new XSSFWorkbook();
    XSSFSheet sheet = workbook.createSheet("TestSheet");
    XSSFRow row ;
    XSSFCell cell;
    JSONArray msg = (JSONArray) jsonObject.get("messages");
    Iterator<String> iterator = msg.iterator();
    while (iterator.hasNext()) {

            row = sheet.createRow(rowNumber);
        cell=   row.createCell(0);
        cell.setCellValue(iterator.next());
        rowNumber=rowNumber+1;
    }
    workbook.write(outStream);
    outStream.close();

    Path path = Paths.get("Test2.xlsx");
    byte[] data = Files.readAllBytes(path);
    return data;

}
public float addValue(float value) {
    return (value + 10);
}
}

so help me to consume the web service.

SimpleDeserializer encountered a child element, which is NOT expected, in something it was trying to deserialize. this error i am getting when i try to invoke client. and another thing input parameter as JSONObject is allowed?

Upvotes: 0

Views: 285

Answers (2)

Cody Patterson
Cody Patterson

Reputation: 138

You can use the package Package javax.ws.rs.

import javax.ws.rs.*;

Here would be a short of example of the library in action: Here is the HTML:

<div>
  Welcome and happy <span id="today"></span>.
  What's your name?
  <input id="name" type="text" autofocus />
  <button id="submit" onclick="greet()">Submit</button>
</div>
<div id="greet">
  <!-- greeting goes here -->
</div>

<script>
// fills in <span id="today">...</span> with today's day of the week
// returned from /rest/today server endpoint
function today() {
  $.get("/rest/today", function(theday) {
      $("#today").text(theday);
    });
};
// fills in <div id="greeting">...</div> with the greeting
// returned from calling the /rest/hello?name=... server endpoint
// with the name from the input text box
function greet() {
  var thename = $("#name").val();
  $.get("/rest/hello", { name: thename }, function(thehello) {
      $("#greet").text(thehello);
    })
    .fail(function(jqXHR, textStatus, errorThrown) {
       // displays server error message, e.g. if called with empty name
       $("#greet").text(textStatus + ": " + errorThrown);
     });
};
$(today); // execute today() after DOM is ready, see https://api.jquery.com/ready/
</script>

</body>
</html>

With corresponding java code:

import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.QueryParam;
import javax.ws.rs.core.Response;

/**
 * REST service that greets requests.
 *
 * This is a "root resource class" as explained in
 * https://jersey.java.net/documentation/latest/jaxrs-resources.html
 */
@Path("/")
public class HelloService {
    @GET
    @Path("/today")
    public String today() {
    return DayOfWeek.today();
    }

    @GET
    @Path("/hello")
    public Response hello(@QueryParam("name") String name) {
        if (name == null || name.isEmpty()) {
            return Response.status(Response.Status.BAD_REQUEST).build();
        } else {
            return Response.ok("hello " + name).build();
        }
    }
}

In order to work with JSON objects, you'll need to use Gson.toJson(). Do something along the lines of this:

String json = new Gson().toJson(some_object);
return Response.ok(json, MediaType.APPLICATION_JSON).build(); 

I hope this was helpful!

Upvotes: 1

flavio
flavio

Reputation: 178

You can try to use Jackson: very good library in which you define you Java object model class that you can convert to JSON or parse from JSON. You will find a lot of examples

Upvotes: 0

Related Questions