gpt4 book ai didi

java - 休息 API 示例

转载 作者:塔克拉玛干 更新时间:2023-11-02 08:38:02 24 4
gpt4 key购买 nike

我有一个用 Java 编写的简单 REST 服务器的实现。每个API调用返回的都是XML格式的数据,如果要格式是JSON怎么办?我需要外部库吗?这是我的代码:

用户.java:

package com.leo;

import java.io.Serializable;

import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;

@XmlRootElement(name = "user")
public class User implements Serializable
{

private static final long serialVersionUID = 1L;
private int id;
private String name;
private String profession;

public User()
{
}

public User(int id, String name, String profession)
{
this.id = id;
this.name = name;
this.profession = profession;
}

public int getId()
{
return id;
}

@XmlElement
public void setId(int id)
{
this.id = id;
}

public String getName()
{
return name;
}

@XmlElement
public void setName(String name)
{
this.name = name;
}

public String getProfession()
{
return profession;
}

@XmlElement
public void setProfession(String profession)
{
this.profession = profession;
}
}

用户道.java

    package com.leo;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.ArrayList;
import java.util.List;

public class UserDao
{
public List<User> getAllUsers()
{
List<User> userList = null;
try
{
File file = new File("Users.dat");
if (!file.exists())
{
User user = new User(1, "Mahesh", "Teacher");
userList = new ArrayList<User>();
userList.add(user);
saveUserList(userList);
}
else
{
FileInputStream fis = new FileInputStream(file);
ObjectInputStream ois = new ObjectInputStream(fis);
userList = (List<User>) ois.readObject();
ois.close();
}
}
catch (IOException e)
{
e.printStackTrace();
}
catch (ClassNotFoundException e)
{
e.printStackTrace();
}
return userList;
}

public User getUser(int id){
List<User> users = getAllUsers();

for(User user: users){
if(user.getId() == id){
return user;
}
}
return null;
}

public int addUser(User pUser)
{
List<User> userList = getAllUsers();
boolean userExists = false;
for (User user : userList)
{
if (user.getId() == pUser.getId())
{
userExists = true;
break;
}
}
if (!userExists)
{
userList.add(pUser);
saveUserList(userList);
return 1;
}
return 0;
}

public int updateUser(User pUser)
{
List<User> userList = getAllUsers();

for (User user : userList)
{
if (user.getId() == pUser.getId())
{
int index = userList.indexOf(user);
userList.set(index, pUser);
saveUserList(userList);
return 1;
}
}
return 0;
}

public int deleteUser(int id)
{
List<User> userList = getAllUsers();

for (User user : userList)
{
if (user.getId() == id)
{
int index = userList.indexOf(user);
userList.remove(index);
saveUserList(userList);
return 1;
}
}
return 0;
}

private void saveUserList(List<User> userList)
{
try
{
File file = new File("Users.dat");
FileOutputStream fos;

fos = new FileOutputStream(file);

ObjectOutputStream oos = new ObjectOutputStream(fos);
oos.writeObject(userList);
oos.close();
}
catch (FileNotFoundException e)
{
e.printStackTrace();
}
catch (IOException e)
{
e.printStackTrace();
}
}
}

用户服务.java

    package com.leo;

import java.io.IOException;
import java.util.List;

import javax.servlet.http.HttpServletResponse;
import javax.ws.rs.Consumes;
import javax.ws.rs.DELETE;
import javax.ws.rs.FormParam;
import javax.ws.rs.GET;
import javax.ws.rs.OPTIONS;
import javax.ws.rs.POST;
import javax.ws.rs.PUT;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.MediaType;

@Path("/UserService")
public class UserService {

UserDao userDao = new UserDao();
private static final String SUCCESS_RESULT="<result>success</result>";
private static final String FAILURE_RESULT="<result>failure</result>";

@GET
@Path("/users")
@Produces(MediaType.APPLICATION_XML)
public List<User> getUsers(){
return userDao.getAllUsers();
}

@GET
@Path("/users/{userid}")
@Produces(MediaType.APPLICATION_XML)
public User getUser(@PathParam("userid") int userid){
return userDao.getUser(userid);
}

@PUT
@Path("/users")
@Produces(MediaType.APPLICATION_XML)
@Consumes(MediaType.APPLICATION_FORM_URLENCODED)
public String createUser(@FormParam("id") int id,
@FormParam("name") String name,
@FormParam("profession") String profession,
@Context HttpServletResponse servletResponse) throws IOException{
User user = new User(id, name, profession);
int result = userDao.addUser(user);
if(result == 1){
return SUCCESS_RESULT;
}
return FAILURE_RESULT;
}

@POST
@Path("/users")
@Produces(MediaType.APPLICATION_XML)
@Consumes(MediaType.APPLICATION_FORM_URLENCODED)
public String updateUser(@FormParam("id") int id,
@FormParam("name") String name,
@FormParam("profession") String profession,
@Context HttpServletResponse servletResponse) throws IOException{
User user = new User(id, name, profession);
int result = userDao.updateUser(user);
if(result == 1){
return SUCCESS_RESULT;
}
return FAILURE_RESULT;
}

@DELETE
@Path("/users/{userid}")
@Produces(MediaType.APPLICATION_XML)
public String deleteUser(@PathParam("userid") int userid){
int result = userDao.deleteUser(userid);
if(result == 1){
return SUCCESS_RESULT;
}
return FAILURE_RESULT;
}

@OPTIONS
@Path("/users")
@Produces(MediaType.APPLICATION_XML)
public String getSupportedOperations(){
return "<operations>GET, PUT, POST, DELETE</operations>";
}
}

编辑:我在我的项目中包含了 jackson jar ,特别是 jackson-core-2.7.0.jar、jackson-databind-2.7.0.jar、jackson-annotations-2.2.1.jar 但现在我从 Tomcat 得到了这个异常:

javax.servlet.ServletException: org.glassfish.jersey.server.ContainerException: java.lang.NoClassDefFoundError: Could not initialize class com.fasterxml.jackson.databind.ObjectMapper
org.glassfish.jersey.servlet.WebComponent.serviceImpl(WebComponent.java:489)
org.glassfish.jersey.servlet.WebComponent.service(WebComponent.java:427)
org.glassfish.jersey.servlet.ServletContainer.service(ServletContainer.java:388)
org.glassfish.jersey.servlet.ServletContainer.service(ServletContainer.java:341)
org.glassfish.jersey.servlet.ServletContainer.service(ServletContainer.java:228)
org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:53)

最佳答案

我正在回答将您的问题解释为与 REST 服务 (UserService.java) 有关的问题,如果这不是预期的,请发表评论。

您必须首先确保方法中的调用确实以 JSON 格式返回结果。这将需要对 User.java 和 UserDao.java 进行适当的更改以返回 JSON 而不是 XML。

您拥有的 User 类示例正在使用 Java JAXB 库,基于那些注释 @XMLRootElement、@XMLElement。

您需要使用支持创建 JSON 对象的 Java 库重写此类。

jackson 图书馆是一个不错的选择。 Here is the home page for Jackson wiki这是有据可查的。

就 REST 服务本身而言,在您的 UserService.java 中,您需要更改服务生成的媒体类型。

更改要从中生成 JSON 的方法注释的所有实例

@Produces(MediaType.APPLICATION_XML)

@Produces(MediaType.APPLICATION_JSON)

关于java - 休息 API 示例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38292457/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com