如何创建简单的Web服务,在java中将输入作为JSONObject

时间:2016-11-30 09:28:40

标签: java web-services

您好我是网络服务新手。

我能够创建简单的Web服务,接受输入字符串并使用eclipse返回另一个字符串。

但是当谈到JSONObject我遇到问题时,在调用Web服务时

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);
}
}

请帮助我使用网络服务。

SimpleDeserializer在尝试反序列化时遇到了一个不期望的子元素。当我尝试调用客户端时,我得到此错误。还有另一个输入参数是JSONObject吗?

2 个答案:

答案 0 :(得分:1)

您可以使用套餐包javax.ws.rs

import javax.ws.rs.*;

这里有一个简短的库实例: 这是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>

使用相应的java代码:

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();
        }
    }
}

为了使用JSON对象,您需要使用Gson.toJson()。做一些事情:

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

我希望这有用!

答案 1 :(得分:0)

您可以尝试使用Jackson:非常好的库,您可以在其中定义Java对象模型类,您可以将其转换为JSON或从JSON解析。 你会发现很多例子