簡體   English   中英

將從JDBC返回的Java String轉換為Json對象

[英]Convert Java String returned from JDBC to Json object

偉大的天才人,我需要幫助解決與java相關的java問題。 在一個程序中,我正在進行JDBC調用,該函數返回一個類似於此的字符串:

[[{PROD_CD=42, SHORT_DESC=WATERFALL EDGE}, {PROD_CD=31, SHORT_DESC=N/A}, {PROD_CD=51, SHORT_DESC=OGEE EDGE}]]

我需要擺脫花括號,逗號,並將其保存為json對象。

[
  {
    "PROD_CD": " 42",
    "SHORT_DESC": "WATERFALL EDGE",
  },
  {
    "PROD_CD": "31",
    "SHORT_DESC": "N/A",
  },
  {
    "PROD_CD": "51",
    "SHORT_DESC": "OGEE EDGE",
  }
]

我非常感謝你的幫助

這是我到目前為止所嘗試的內容:

@Override
    public Map<String, String> getEdgeCd() {


        Map<String, String> EdgeCd = new HashMap<String, String>();
        Map<String,Object> temp = new HashMap<String,Object>();


        try {


            SimpleJdbcCall fgetEdgeCd = new SimpleJdbcCall(jdbcTemplate)
                    .withSchemaName("logprd")
                    .withCatalogName("edge_api_pkg")
                    .withFunctionName("DDGetEdgeCd");


            temp = fgetEdgeCd.execute();
            System.out.println("temp " + temp + "  \n\n\n\n\n\n");
            System.out.println("temp.values() " + temp.values() + " lines \n\n\n\n\n\n");

            String keyList =  temp.values().toString();

//這回到了以下字符串:

String keyList =  "[[{PROD_CD=42, SHORT_DESC=WATERFALL EDGE}, {PROD_CD=31, SHORT_DESC=N/A}, {PROD_CD=51, SHORT_DESC=OGEE EDGE}]]"; 
String[] currentLine;

currentLine = keyList.substring(3, keyList.length() -3).split("[}]|[{]");
String currenLineString = Arrays.toString(currentLine);

String newCurrentLineString = currenLineString.substring(1, keyList.length()-1).replaceAll("," , "").replaceAll(" EDGE" , "-Edge").replaceAll("\\s+", " ");
//System.out.println("newCurrentLineString:>"+ newCurrentLineString + "\n\n");
String[] testLine;
testLine = newCurrentLineString.split(" ");


ArrayList<LinkedHashMap<String, Object>> data = new ArrayList<LinkedHashMap<String, Object>>();
LinkedHashMap<String, Object> map=new LinkedHashMap<String, Object>();
Collection<String> keyValue = null;
    for(int i=0; i< testLine.length; i++) {
     String[] temp = testLine[i].toString().split("=");
    keyValue.addAll(Arrays.asList(temp));
    System.out.println( "keyValue"+i + ":>"+ keyValue.toString() + "\n\n");

    for (int j=0; j < keyValue.size(); j+=2) {
     map.put(temp[j].toString(), temp[j+1].toString());
     //map.put(keyValue[i].toString(), keyValue[i+1].toString());
     //System.out.println( "mapmain:>"+ map.toString() + "\n\n");
     data.add(map);
     System.out.println(map.toString());
     System.out.println(data.toString());

    }//end for j
   }end for i
      } catch (Exception e) {

            logger.error("Error trying JDBC");
    }

        return EdgeCd;
    }

}

這是一個答案,但不一定是你想要的答案。

  1. 查看從數據庫返回的數據。 請注意,它有一個明顯的模式。
  2. 數據庫中有三個基本對象從數據庫返回; 數組,容器對象,鍵值對。 該數組是容器對象的數組。 容器對象包含一個或多個鍵值對。 鍵值對由兩個String值組成。
  3. 創建一個解析器,用於解析從數據庫返回的數據。 我建議不要試圖用正則表達式“修復”它,只需用代碼解析它。
  4. 使用上面提到的三個對象,使用解析器創建數據的對象表示(也在上面提到)。
  5. 將對象輸出為json。

這是C#中的一個快速功能,可以輕松移植到JAVA(抱歉,我的手機上沒有JAVA編譯器)。 如果大括號或逗號出現在記錄數據中,主要問題將是假設空格和轉義字符。

        string data = "[[{PROD_CD=42, SHORT_DESC=WATERFALL EDGE}, {PROD_CD=31, SHORT_DESC=N/A}, {PROD_CD=51, SHORT_DESC=OGEE EDGE}]]";

        char[] chars = data.ToCharArray();
        StringBuilder currentRecord = null;
        StringBuilder json = new StringBuilder("[");

        bool isInCurly = false;// Loop state 
        for (int i=0;i<chars.Length; ++i)
        {
            if (chars[i] == '{')
            {
                isInCurly = true;
                currentRecord = new StringBuilder("{");
            }
            else if (chars[i] == '}')
            {
                currentRecord.Append("}");
                isInCurly = false;

                // Major assumptions made here about the structure that will need to be verified such as ", " between record values, etc...
                string cleanRecord = currentRecord.ToString().Replace("{", "{\"")
                                                             .Replace("=", "\":\"")
                                                             .Replace(", ", "\", \"")
                                                             .Replace("}", "\"}");
                json.AppendLine(cleanRecord + ", ");
            }
            else if(isInCurly)
            {
                currentRecord.Append(chars[i]);
            }
        }            
        json.Append("]");
        string finalJson = json.ToString();

結果 在此輸入圖像描述

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM