2017-06-13 30 views
0

在我的'PlayerLocation'servlet中,我得到'緯度,經度和名稱'如下;如何將'double'userLati,userLong值和String userName傳遞給Json變量/對象

 String userLatitude = request.getParameter("currentLat"); 
    String userLongitude = request.getParameter("currentLong"); 
    double userLati = Double.parseDouble(userLatitude);   
    double userLong = Double.parseDouble(userLongitude);   
    DecimalFormat dFormat = new DecimalFormat("#.########"); 
    userLati= Double.valueOf(dFormat .format(userLati)); 
    userLong= Double.valueOf(dFormat .format(userLong)); 
    String userName = request.getParameter("name");   

我想要在JSP中接收經緯度和名稱以及servlet響應。 如何將'double'userLati,userLong值和String userName傳遞給Json變量/對象;

 String data = ///??????? 
     String json = new Gson().toJson(data);   
     response.setContentType("application/json"); 
     response.setCharacterEncoding("UTF-8"); 
     response.getWriter().write(json); 

請問有人能告訴我如何做到這一點?

回答

0

你應該讓球員細節POJO和領域應該是你在想各自類型的你的迴應。下面是示例代碼:

你PlayerDetails類應該看起來像

class PlayerDetails{ 
private String name; 
private double latitude; 
private double longitude; 

    public PlayerDetails(String name, double latitude, double longitude) { 
     this.name = name; 
     this.latitude = latitude; 
     this.longitude = longitude; 
    } 

    //Getter and Setters 
} 

在你的servlet做:

PlayerDetails playerDetails=new 
          PlayerDetails(userName,userLati,userLong); 
    String jsonResponse = new Gson().toJson(playerDetails); 

現在你可以寫jsonResponse來響應。上面的代碼示例響應:

{ 
    "name": "user1", 
    "latitude": 51.503364, 
    "longitude": -0.127625 
} 

PS:一個設計原則是,你可以創建一個名爲PlayerLocation用經緯度POJO,並讓它成爲PlayerDetails的一部分。這會更清潔。 在這種情況下,你的JSON響應將是

{ 
    "name": "user1", 
    "location": { 
    "latitude": 51.503364, 
    "longitude": -0.127625 
    } 
} 
+0

也會嘗試,並儘快更新。 – soccerway

0

我認爲,如果你這樣做

class PlayerLocation { 
String currentLat; 
String currentLong; 
String name; 

public PlayerLocation(String currentLat, String currentLong, String name){ 
    this.currentLat = currentLat; 
    this.currentLong = currentLong; 
    this.name = name; 
} 
} 

,然後改變你的字符串數據= // ???到一個新的PlayerLocation對象,你可以使它看起來像這樣:

PlayerLocation data = new PlayerLocation(/* data here */); 
String json = new Gson().toJson(data); 

而且我認爲它應該工作。

我引用這一點:https://github.com/google/gson/blob/master/UserGuide.md#TOC-Object-Examples

+0

會嘗試更新 – soccerway

1

您也可以以這種方式使用HashMap

HashMap map = new HashMap<String, Object>(); 
map.put("userLati", 23); 
map.put("userLong", 45); 
map.put("userName", "mr pro"); 
String json = new Gson().toJson(data); 
+0

這是一個不好的做法。請不要使用這種方式。 –

+0

@PriyaJain你能告訴我更多的細節嗎?爲什麼這是一個不好的做法? –

+0

Java是一種面向對象的語言。創建一張地圖並將其放入其中,這的確是可行的解決方案,但是違背了OO原則。該解決方案應該具有類模型而不是硬編碼映射。 –