Java 将数据库详细信息转换为 JSON 对象

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/21110537/
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 06:38:37  来源:igfitidea点击:

Converting the Database details to JSON object

javajson

提问by Amit Sharad

I have a table with has the columns namely

我有一张表,其中有列

recordID, recordName , titleFeild, titleIDMap, titleId, titleStartDate, titleEndDate, languageId

recordID、recordName、titleFeild、titleIDMap、titleId、titleStartDate、titleEndDate、languageId

Now I have convert the data from above columns to the JSON object data which looks like below

现在我已将数据从上面的列转换为 JSON 对象数据,如下所示

{
  "recordId" :10,
  "recordName" : "RECORDS",
  "records" : [ {
    "titleField" : 1,
    "titleIDMap" : null,
    "titleId" : 500,
    "titleStartDate" : "2013-12-22T00:00:00.000+0000",
    "titleEndDate" : "2013-12-03T00:00:00.000+0000",
    "languageId" : 20
  }]
}

Please note that recordsis an array of columns( titleFeild,titleIDMap,titleId,titleStartDate,titleEndDate,languageId)

请注意,记录是一个列数组(titleFeild、titleIDMap、titleId、titleStartDate、titleEndDate、languageId)

The code so far I have developed is

到目前为止我开发的代码是

    List<Object[]> objList = dao.getStatus();
    Integer result = null;
     JSONObject jsonData = new JSONObject();
     JSONArray jsonDataArray = new JSONArray();
    if(objList!=null && objList.size()>10000)
        {
            for (Object[] nameObj : objList) {

                jsonData.put("", nameObj.get(arg0) );


            }
        }

How do I construct the JSON Object from the columns data ?

如何从列数据构造 JSON 对象?

采纳答案by PopoFibo

You can easily achieve this with google-gsonlibrary. In simple terms you would have to create a couple of Pojos(with reference to another containin a list of references).

您可以使用google-gson库轻松实现这一点。简单来说,您必须创建几个Pojo(参考包含在参考列表中的另一个)。

Consider RecordIDand RecordNameas Meta Data.

考虑RecordIDRecordName作为元数据

Create a pojorepresenting this information:

创建一个pojo代表此信息的:

public class DbMetaPojo {

    private int recordID;
    private String recordName;
    private List<Record> records;

    public List<Record> getRecords() {
        return records;
    }

    public void setRecords(List<Record> records) {
        this.records = records;
    }

    public String getRecordName() {
        return recordName;
    }

    public void setRecordName(String recordName) {
        this.recordName = recordName;
    }

    public int getRecordID() {
        return recordID;
    }

    public void setRecordID(int recordID) {
        this.recordID = recordID;
    }

}

Create another pojowith the actual Recordfields:

pojo使用实际Record字段创建另一个:

public class Record {

    public int getTitleFeild() {
        return titleFeild;
    }

    public void setTitleFeild(int i) {
        this.titleFeild = i;
    }

    public String getTitleIDMap() {
        return titleIDMap;
    }

    public void setTitleIDMap(String titleIDMap) {
        this.titleIDMap = titleIDMap;
    }

    public int getTitleId() {
        return titleId;
    }

    public void setTitleId(int titleId) {
        this.titleId = titleId;
    }

    public String getTitleStartDate() {
        return titleStartDate;
    }

    public void setTitleStartDate(String titleStartDate) {
        this.titleStartDate = titleStartDate;
    }

    public String getTitleEndDate() {
        return titleEndDate;
    }

    public void setTitleEndDate(String titleEndDate) {
        this.titleEndDate = titleEndDate;
    }

    public int getLanguageId() {
        return languageId;
    }

    public void setLanguageId(int languageId) {
        this.languageId = languageId;
    }

    private int titleFeild;
    private String titleIDMap;
    private int titleId;
    private String titleStartDate;
    private String titleEndDate;
    private int languageId;

}

Now just a method to populate your POJOswith the relevant data (replace the hardcoding logic with your data retrieve):

现在只是一种POJOs用相关数据填充您的方法(用您的数据检索替换硬编码逻辑):

public static void main(String... main) {
        DbMetaPojo obj = new DbMetaPojo();

        obj.setRecordID(10);
        obj.setRecordName("RECORDS");

        Record record = new Record();

        record.setLanguageId(20);
        record.setTitleEndDate("2013-12-22T00:00:00.000+0000");
        record.setTitleFeild(1);
        record.setTitleId(500);
        record.setTitleIDMap("SOME NULL");
        record.setTitleStartDate("2013-12-22T00:00:00.000+0000");

        List<Record> list = new ArrayList<Record>();
        list.add(record);
        obj.setRecords(list);

        Gson gson = new Gson();

        String json = gson.toJson(obj);

        System.out.println(json);
    }

Output is your formed JSON:

输出是您形成的 JSON:

{
    "recordID": 10,
    "recordName": "RECORDS",
    "records": [
        {
            "titleFeild": 1,
            "titleIDMap": "SOME NULL",
            "titleId": 500,
            "titleStartDate": "2013-12-22T00:00:00.000+0000",
            "titleEndDate": "2013-12-22T00:00:00.000+0000",
            "languageId": 20
        }
    ]
}

EDIT:

编辑:

To align to your code, you might want to do something like:

要与您的代码保持一致,您可能需要执行以下操作:

List<Object> objList = dao.getStatus();
        List<DbMetaPojo> metaList = new ArrayList<DbMetaPojo> ();
        if (objList != null && objList.size() > 10000) {
            for (Object nameObj : objList) {
                DbMetaPojo meta = new DbMetaPojo();
                meta.setRecordID(nameObj[0]);
                meta.setRecordName(nameObj[0]);
                ...
                ...
                ...

                metaList.add(meta);
            }
        }

回答by Vinayak Pingale

  1. First of all what you have to do is retrieve the data from the columns of the table using your DAOand calling a Function from DAOIMPLwhich in turn will return the list of data(POJOprobably).
  1. 首先,您需要做的是使用您的DAO并调用一个函数从表的列中检索数据,该函数DAOIMPL又将返回数据列表(POJO可能)。

Create a map like this which will contain your key value pair for example recordid and value, recordname and value

创建一个这样的映射,其中将包含您的键值对,例如记录 ID 和值、记录名称和值

Map<String,Object> objMap = new HashMap<String,Object>();
    objMap.put("recordId", Record.getId());
    objMap.put("recordName",Record.getName());
    // Now here is the deal create another hashmap here whose key will be records "the key for your second array" 
    //Put the values in this second hashmap as instructed above and put it as a key value pair.
    ........
    .......
    .......
    JSONObject JsonObject = JSONObject.fromObject(objMap);//This will create JSON object out of your hashmap.
    objJSONList.add(JsonObject);
}


StringBuffer jsonBuffer = new StringBuffer();
    jsonBuffer.append("{\"data\": {");
    jsonBuffer.append(objJSONList.tostring());
    jsonBuffer.append("}");
    //jsonBuffer.append(",\"total\":"+ objJSONList.size());// TOTAL Optional
    //jsonBuffer.append(",\"success\":true}");//SUCCESS message if using in callback Optional

回答by Tugrul

Create an object which has your attribues. (recordID, recordName , titleFeild, titleIDMap, titleId, titleStartDate, titleEndDate, languageId)

创建一个具有您的属性的对象。(记录ID、记录名称、titleFeild、titleIDMap、titleId、titleStartDate、titleEndDate、languageId)

Get data from dao and convert it to json. It will looks like what you want.

从 dao 获取数据并将其转换为 json。它看起来像你想要的。

Gson gson = new Gson();

    // convert java object to JSON format,
    // and returned as JSON formatted string
    String json = gson.toJson(obj);

回答by user3192244

I think your dao.getStatus() should return a List with Map keys and values. Your key would be column name and value would be content.

我认为你的 dao.getStatus() 应该返回一个带有 Map 键和值的列表。您的键是列名,值是内容。

List<Map<String,Object>> objList = dao.getStatus();
if(objList!=null && objList.size()>10000){
   for(Map<String,Object> row : objList) {
       Iterator<String> keyList = row.keySet().iterator();
       while(keyList.hasNext()){
          String key = keyList.next();
          jsonData.put(key, row.get(key));
       }
   }
}

For the records array you need to build it while iterating table columns. Combining above code with building records array would be something like this..

对于记录数组,您需要在迭代表列时构建它。将上面的代码与构建记录数组相结合将是这样的..

    String[] group = {"titleField","titleIDMap","titleId","titleStartDate","titleEndDate","languageId"};
    List<String> recordGroup = Arrays.asList(group);
    Map<Object, JSONArray> records = new HashMap<Object,JSONArray>();
    List<Map<String,Object>> objList = dao.getStatus();
    JSONObject jsonData = new JSONObject();
    if(objList!=null && objList.size()>10000){
       for(Map<String,Object> row : objList) {
           int columnCount = 0;
           Iterator<String> keyList = row.keySet().iterator();

           while(keyList.hasNext()){
              String key = keyList.next();

              if(recordGroup.contains(key)){
                  Object recordId = row.get("recordId");
                  JSONArray recordArray = new JSONArray();
                  if(records.containsKey(recordId)){
                      recordArray = records.get(recordId);
                      JSONObject jsonObj = null;
                      if(columnCount >= recordGroup.size()){
                         jsonObj = new JSONObject();
                         recordarray.add(jsonObj);
                         columnCount = 0; 
                      }
                      else {
                         jsonObj = (JSONObject) recordArray.get(recordArray.size()-1);
                      }
                      jsonObj.put(key, row.get(key));
                      columnCount++;
                  }
                  else {
                      JSONObject jsonObj = new JSONObject();
                      jsonObj.put(key, row.get(key));
                      recordArray.add(jsonObj);
                      records.put(recordId, recordArray);
                  }
                  jsonData.put("records", records.get(recordId));
              }
              else {
                  jsonData.put(key, row.get(key));
              }
           }
       }
    }