Axis2是一個(gè)自Apache編寫的Java Web服務(wù)框架。Axis2支持RESTful架構(gòu)的Web服務(wù),并且能夠以JSON格式返回?cái)?shù)據(jù)。在本文中,我們將通過(guò)一個(gè)簡(jiǎn)單的示例來(lái)演示如何在Axis2中返回JSON。
首先,我們需要?jiǎng)?chuàng)建一個(gè)簡(jiǎn)單的RESTful Web服務(wù)。以下是一個(gè)示例代碼:
import org.apache.axis2.context.ConfigurationContext; import org.apache.axis2.context.ConfigurationContextFactory; import org.apache.axis2.description.AxisService; import org.apache.axis2.engine.AxisConfiguration; import org.apache.axis2.transport.http.SimpleHTTPServer; import javax.xml.namespace.QName; public class RestService { public static void main(String[] args) throws Exception { ConfigurationContext configurationContext = ConfigurationContextFactory.createConfigurationContextFromFileSystem(null, null); AxisConfiguration axisConfiguration = configurationContext.getAxisConfiguration(); AxisService axisService = new AxisService(new QName("restService")); axisService.addParameter("ServiceClass", RestService.class.getName()); axisConfiguration.addService(axisService); SimpleHTTPServer server = new SimpleHTTPServer(configurationContext, 8080); server.start(); } public String hello(String name) { return "Hello " + name + "!"; } }
在上面的示例代碼中,我們創(chuàng)建了一個(gè)名為restService的Axis2服務(wù)并運(yùn)行在本地的8080端口。服務(wù)類是RestService,并且有一個(gè)簡(jiǎn)單的hello方法,返回“Helloname!”這個(gè)字符串。當(dāng)訪問(wèn)http://localhost:8080/restService/hello/name時(shí),將觸發(fā)hello方法并返回結(jié)果。
接下來(lái),我們需要配置Axis2以返回JSON格式的數(shù)據(jù)。為此,我們需要在服務(wù)類中添加以下注釋:
import org.apache.axis2.databinding.utils.BeanUtil; import org.apache.axis2.json.JSONStreamBuilder; import org.apache.axis2.json.gson.GsonConduitJSONStreamWriter; import javax.ws.rs.*; import java.io.StringWriter; @Path("hello") public class RestService { @GET @Path("/{name}") @Produces("application/json") public String hello(@PathParam("name") String name) throws Exception { String message = "Hello " + name + "!"; StringWriter stringWriter = new StringWriter(); GsonConduitJSONStreamWriter jsonStreamWriter = new GsonConduitJSONStreamWriter(stringWriter); JSONStreamBuilder jsonStreamBuilder = new JSONStreamBuilder(); BeanUtil.serialize(jsonStreamBuilder, null, message); jsonStreamWriter.write(jsonStreamBuilder.build()); jsonStreamWriter.flush(); return stringWriter.toString(); } }
在上面的代碼中,我們使用注釋@Path和@Produces("application/json")來(lái)指定服務(wù)的路徑和返回類型。在hello方法中,我們使用GsonConduitJSONStreamWriter將Java對(duì)象轉(zhuǎn)換為JSON字符串。
最后,在瀏覽器中輸入http://localhost:8080/restService/hello/name,您將看到如下結(jié)果:
"Helloname!"
在這里,我們成功地返回了一個(gè)JSON格式的數(shù)據(jù)!