【问题标题】:Desired Json Output Java所需的 Json 输出 Java
【发布时间】:2017-09-08 23:09:50
【问题描述】:

我是 Java 和 Json 的新手。我想问一下如何获得以下Json输出。

{
"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;
}

我在 Postman 中的输出是

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

我希望得到如顶部 Json 输出所示的输出。我该怎么做?

【问题讨论】:

    标签: java mysql json


    【解决方案1】:

    您的输出是您返回的数据的 Json 表示形式。

    以下方法返回AppData 类型的对象,它是您的appdatas 映射的值。

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

    如果要更改输出,则返回相应的数据、键 (AppDataRequest) 对象和值 (AppData) 对象。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-10-09
      • 2012-11-08
      • 2018-01-21
      • 1970-01-01
      • 2017-07-04
      • 2021-03-26
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多