如何使用Jersey Rest Web Services和Java解析JSON数组

时间:2014-01-08 07:49:17

标签: java json web-services jersey arrays

我从iOS客户端获取Json数组,并希望使用Java和jersey以及Gson解析服务器端的Json。我从iOS发送POST方法中的JSON数组。我想使用json但是如何在Java类中保存json数据。这是我的Json数组的结构

{
    "friendList": [
      {"id": 1, "username": "user1", "name":"person1", "friendUsername":"fUser1", "friendName":"fName1"},
      {"id": 2, "username": "user2", "name":"person2", "friendUsername":"fUser2", "friendName":"fName2"},
      {"id": 3, "username": "user3", "name":"person3", "friendUsername":"fUser3", "friendName":"fName3"},...
    ]
}

这是我的网络服务类

@Path("/FriendsList")
public class RestWebServicesAPI {


     @POST
     @Path("/friends")
     @Consumes(MediaType.APPLICATION_JSON)
     public Friends saveFriedList(Friends friend, @Context HttpServletRequest request) {

        // Don't know how to parse json array????

     }


}

这是我的朋友班

import java.util.List; 

import javax.xml.bind.annotation.XmlRootElement; 

@XmlRootElement 

Public Class Friends {

    private String id; 
    private String username; 
    private String name; 
    private String friendUsername; 
    private String friendName;  

    public Friends() { 
    } 

   //getter setter methods

} 

2 个答案:

答案 0 :(得分:5)

我认为你必须这样做:

@Path("/FriendsList")
public class RestWebServicesAPI{

@POST
@Path("/friends")
@Consumes(MediaType.APPLICATION_JSON)
public Friends saveFriendList(final String json){
    Gson gs = new Gson();
    Friends [] n = gs.fromJson(json, Friends [].class);

}
//ALTERNATIVE
@POST
    @Path("/friends")
    @Consumes(MediaType.APPLICATION_JSON)
    public Friends saveFriendList(final Friends[] friends){


    }

答案 1 :(得分:0)

请遵循以下来源

@POST
@Path("/friends")
@Consumes(MediaType.APPLICATION_JSON)
public Friends saveFriendList(Friends friends){
 // saveFriend function should have business logic to store your data in db
 friends= saveFriend(friends);
}