簡體   English   中英

如何使用Jersey Rest Webservices和Java解析JSON數組

[英]How to parse JSON array using Jersey Rest Webservices and Java

我從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){


    }

請遵循以下來源

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM