2017-04-13 45 views
1

我是Java annd Json的新手。我想問一下如何獲得下面的Json輸出。所需的Json輸出Java

{ 
"AppData": { 
    "status": "****", 
    "message": [ 
     "" 
    ] 
}, 
"Data": { 
    "token": "****" 
} 

我使用以下代碼

}。 從數據庫中檢索數據的代碼,導入HashMap並從HashMap中檢索。

HashMap<AppDataRequest, AppData> appdatas = new HashMap<AppDataRequest, AppData>(); 

static final String JDBC_DRIVER = "com.mysql.jdbc.Driver"; 
static final String DB_URL = "jdbc:mysql://****:3306/****"; 

static final String USER = "****"; 
static final String PASS = "****"; 

public AppDataService(){ 
    Connection conn = null; 
    Statement stat = null; 
    try{ 
     Class.forName("com.mysql.jdbc.Driver"); 
     conn = DriverManager.getConnection(DB_URL, USER, PASS); 
     stat = conn.createStatement(); 
     String sql = "SELECT * FROM testdata"; 
     ResultSet resu = stat.executeQuery(sql); 
     while(resu.next()){ 
      int id = resu.getInt("app_id"); 
      String email = resu.getString("email"); 
      String password = resu.getString("password"); 
      String token = resu.getString("token"); 
      appdatas.put(new AppDataRequest(id, email, password), new AppData(" ", "success", token)); 
     } 
     resu.close(); 
     stat.close(); 
     conn.close(); 
    } 
    catch(SQLException se){ 
     se.printStackTrace(); 
    } 
    catch(Exception e){ 
     e.printStackTrace(); 
    } 
    finally{ 
     try{ 
      if(stat!=null){ 
       stat.close(); 
      } 
     } 
     catch (SQLException se2){ 

     } 
     try{ 
      if(conn!=null){ 
       conn.close(); 
      } 
     } 
     catch(SQLException se3){ 
      se3.printStackTrace(); 
     } 
    }  
} 

public AppData getSAppData(int id, String email, String password){ 
    return appdatas.get(new AppDataRequest (id, email, password)); 
} 

代碼POST

@POST 
@Path("/appdatas") 
public AppData getSAppData(AppDataRequest adr) { 
    AppData appdata = ads.getSAppData(adr.getId(), adr.getEmail(), adr.getPassword()); 
    if(appdata == null){ 
     throw new DataNotFoundException(" "); 
    } 
    return appdata; 
} 

和我的郵差輸出

{ 
    "message": "****", 
    "status": "****", 
    "token": "****" 
} 

我希望得到的輸出如在頂部的JSON輸出。我該怎麼做?

回答

0

您的輸出是您返回的數據的Json表示。

以下方法返回類型爲AppData的對象,它是appdatas圖的值。

public AppData getSAppData(int id, String email, String password){ 
    return appdatas.get(new AppDataRequest (id, email, password)); 
} 

如果你想改變輸出,然後返回相應的數據,密鑰(AppDataRequest)對象和值(AppData)對象。