我从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"},...
]
}
这是我的Web服务类
@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
}
解决方法:
我想你必须这样做:
@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){
}