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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/20989792/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-13 05:46:38  来源:igfitidea点击:

How to parse JSON array using Jersey Rest Webservices and Java

javajsonweb-servicesjerseyarrays

提问by Suhit Patil

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

我正在从 iOS 客户端获取 Json 数组,并希望使用 Java、球衣和 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"},...
    ]
}

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

} 

采纳答案by fabuloso

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


    }

回答by user1584844

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