简体   繁体   中英

How to parse JSON array using Jersey Rest Webservices and Java

I am getting Json array from iOS client and want to parse the Json in server side using Java and jersey and Gson. I am sending the JSON array in POST method from iOS. I want to consume the json but stuck on how do i save the json data in Java class. This is the structure of my Json array

{
    "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"},...
    ]
}

Here is my web services Class

@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????

     }


}

and Here is my Friends Class

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

} 

I think you have to do simply like this:

@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){


    }

Please follow the below source

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM