How to parse a JsonString into key value pairs? - java

I have a PostRequest here that I want to be able to save data to different tables. About the #RequestBody I get a JsonString that I want to split to be able to execute an INSERT INTO query.
Here is my PostRequest:
#PostMapping(value = "/config/test/{tableName}/{schemaName}")
public String postValue(#RequestBody String values, #PathVariable("tableName") String tableName, #PathVariable("schemaName") String schemaName) {
String keyString = "";
String valueString = "";
final String sql = "INSERT INTO " + schemaName + "." + tableName + "(" + keyString + ") VALUES(" + valueString + ")";
final Query query = em.createNativeQuery(sql);
query.executeUpdate();
return values;
}
And here's my JSONString:
{
"id": 23,
"indexNummer": 4,
"indexName": "Gewichtung Alter Periode ohne Maßnahmen",
"minVal": 51.0,
"maxVal": 85.0,
"indexWert": 1
}
Is there any way to split my string so that my two strings keyString, valueString are filled as follows?
keyString = "id,indexNumber,indexName,minVal,maxVal,indexValue"
valueString="23,4, "Is there any way to split my string so that my two strings keyString, valueString are filled as follows?
keyString = "id, indexNumber, indexName, minVal, maxVal, indexValue"
valueString="23, 4, "Gewichtung Alter Periode ohne Maßnahmen", 51.0, 85.0, 1"

You can convert JSONString into Map or you can directly read it is map and then do the following
#PostMapping(value = "/config/test/{tableName}/{schemaName}")
public Map postValue(#RequestBody Map<String, Object> values, #PathVariable("tableName") String tableName,
#PathVariable("schemaName") String schemaName) {
String keyString = "";
String valueString = "";
Set<String> keySet = values.keySet();
for (String key : keySet) {
// add comma after first key-value pair only.
if (keyString.length() > 0) {
keyString += ",";
valueString += ",";
}
keyString += key;
Object valueObj = values.get(key);
if (valueObj instanceof String) {
valueString = valueString + "\"" + valueObj.toString() + "\"";
} else if (valueObj instanceof Integer) {
Integer valueInt = (Integer) valueObj;
valueString = valueString + valueInt;
} else if (valueObj instanceof Double) {
Double valueDouble = (Double) valueObj;
valueString = valueString + valueDouble;
}
}
final String sql = "INSERT INTO " + schemaName + "." + tableName + "(" + keyString + ") VALUES(" + valueString + ")";
final Query query = em.createNativeQuery(sql);
query.executeUpdate();
return values;
}

Use com.fasterxml.jackson.databind.ObjectMapper as below:
ObjectMapper mapper =new ObjectMapper();
String string="{\r\n"
+ " \"id\": 23,\r\n"
+ " \"indexNummer\": 4,\r\n"
+ " \"indexName\": \"Gewichtung Alter Periode ohne Maßnahmen\",\r\n"
+ " \"minVal\": 51.0,\r\n"
+ " \"maxVal\": 85.0,\r\n"
+ " \"indexWert\": 1\r\n"
+ "}";
TypeReference<HashMap<String, String>> typeRef = new TypeReference<HashMap<String, String>>() {
};
HashMap<String, String> map = mapper.readValue(string, typeRef);
String keys = map.keySet().stream().collect(Collectors.joining(","));
String values = map.values().stream().collect(Collectors.joining(","));
System.out.println(keys);
System.out.println(values);
Output :
indexNummer,maxVal,minVal,indexName,id,indexWert
4,85.0,51.0,Gewichtung Alter Periode ohne Maßnahmen,23,1

Related

How can I set the x-axis and y-axis in charts

How can I set the x-axis and y-axis in charts?
Here labels are displayed. But I want to display the x-axis and y-axis names(label) in the chart graph.
public class ChartUtils {
public static HashMap<String, String> getChartData(String projectName, String questionnaireName, String questionId,
String questionValue) throws Exception {
HashMap<String, String> cMap = new HashMap<String, String>();
String dailyResponseCounts = "";
String responseStringValues = "";
String responseStringValuesForTable = "";
int cumulativeCount = 0;
String questionniareSql = "Select questionnairedetails from questionnairedetails where projectname='"
+ projectName + "' and questionnairename='" + questionnaireName + "'";
String sql = " SELECT response, count(*) as count FROM surveyresponsedetails where isduplicate is null and surveydetailsid in ("
+ " select generalkey from surveydetails where questionnaireid in ("
+ " select generalkey from questionnairedetails where projectname='" + projectName
+ "' and questionnairename='" + questionnaireName + "' " + " )and question like '"
+ StringEscapeUtils.escapeSql(org.apache.commons.lang3.StringEscapeUtils.unescapeHtml4(questionValue))
+ "') " + " and response is not null and response <> '' group by response order by count asc";
// String legendString="";
String tableHTML = "";
String questionnaireJsonDB = "";
JsonArray optionsArray = new JsonArray();
boolean isMultiChoice = false;
try {
// Get the questionnaire JSON for this entry.
questionnaireJsonDB = new ConnectionFactory().getString(questionniareSql);
// Condition :1 && 2
if (!questionnaireJsonDB.equals("") && questionnaireJsonDB.contains(questionValue)) {
JsonObject questionnaireJson = (JsonObject) new JsonParser().parse(questionnaireJsonDB);
for (String key : questionnaireJson.keySet()) {
if (!key.equals("questionnaireTitle")) {
JsonObject sections = (JsonObject) questionnaireJson.get(key);
// get the questions
for (String key1 : sections.keySet()) {
if (key1.equals("questions")) {
JsonArray questions = (JsonArray) sections.get(key1);
for (int i = 0; i < questions.size(); i++) {
JsonObject indQuestions = (JsonObject) questions.get(i);
String questName = indQuestions.get("questionTitle").getAsString();
if (!questName.equals(questionValue)) {
continue;
}
// Condition 3
String qType = indQuestions.get("questionType").getAsString();
if (qType.equals("radio") || qType.equals("checkbox")) {
optionsArray = indQuestions.get("options").getAsJsonArray();
isMultiChoice = true;
}
}
}
}
}
}
} // End of condition 1 & 2
} catch (Exception e) {
System.out.println("Exception during retrieval of Questionnaire details with SQL : " + questionniareSql);
}
// Get the data values for the charts.
List<Map<String, String>> records = new ConnectionFactory().getArrayForSql(sql);
int i = 0;
final DecimalFormat df = new DecimalFormat("0.00");
float totalCount = 0;
if (records.size() > 0) { // Check if any records are returned from the DB.
tableHTML = "<TR><TH>Response</TH><TH>Count</TH></TR>";
HashMap<String, String> tableMap = new HashMap<String, String>();
for (Map<String, String> record : records) {
String countString = record.get("count");
int countPer = StringUtils.getIntFromString(countString);
totalCount = countPer + totalCount;
System.out.println("totalCount "+totalCount);
}
for (Map<String, String> record : records) {
String responseString = record.get("response");
String countString = record.get("count");
if (isMultiChoice) {
tableMap.put(responseString, countString);
} else {
tableHTML = tableHTML + "<TR id=" + questionId + "_piechart" + "_" + i + "><TD>"
+ StringEscapeUtils.escapeJava(responseString) + "</TD><TD>" + countString + "</TD></TR>";
// legendString=legendString+"<span class='dot' style='background-color:"+
// customColors[i % customColors.length]+"'></span><span
// style='margin-left:10px;margin-left:3px;'>"+ responseString +"</span>";
i++;
int count = StringUtils.getIntFromString(countString);
cumulativeCount = cumulativeCount + count;
//dailyResponseCounts = dailyResponseCounts + "" + count + ",";
if(count!=0) {
String per = df.format((count/totalCount)*100);
System.out.println(totalCount);
dailyResponseCounts = dailyResponseCounts + "" + per + ",";
System.out.println(dailyResponseCounts);
}
String responseStringVal = "\"" + StringEscapeUtils.escapeJava(responseString) + "\"";
responseStringValuesForTable = responseStringValuesForTable + responseStringVal + ",";
// String [] responseStringArray = responseString.split(" ");
if (responseString.length() > 15) {
responseStringVal = "\"" + StringEscapeUtils.escapeJava(responseString.substring(0, 14))
+ "...\"";
} else {
responseStringVal = "\"" + StringEscapeUtils.escapeJava(responseString) + "\"";
}
responseStringValues = responseStringValues + "" + responseStringVal + ",";
}
}
if (isMultiChoice) {
for (int s = 0; s < optionsArray.size(); s++) {
JsonObject indOptions = (JsonObject) optionsArray.get(s);
String optionValue = indOptions.get("value").getAsString();
String optionValue1 = optionValue;
for (char c : optionValue.toCharArray()) {
if (c > 127) {
int sIndex = optionValue.indexOf(c);
// System.out.println(sIndex);
String replaced = optionValue.substring(sIndex);
optionValue1 = optionValue.replace(replaced, "");
// System.out.println(optionValue1);
break;
}
}
tableHTML = tableHTML + "<TR id=" + questionId + "_piechart" + "_" + s + "><TD>" + optionValue1
+ "</TD><TD>" + ObjectUtils.defaultIfNull(tableMap.get(optionValue), "0") + "</TD></TR>";
int count = StringUtils
.getIntFromString((String) ObjectUtils.defaultIfNull(tableMap.get(optionValue), "0"));
cumulativeCount = cumulativeCount + count;
//dailyResponseCounts = dailyResponseCounts + "" + count + ",";
if(count!=0) {
String per = df.format((count/totalCount)*100);
System.out.println(totalCount);
dailyResponseCounts = dailyResponseCounts + "" + per + ",";
System.out.println(dailyResponseCounts);
}
String responseStringVal = "\"" + optionValue1 + "\"";
responseStringValuesForTable = responseStringValuesForTable + responseStringVal + ",";
// String [] responseStringArray = optionValue.split(" ");
if (optionValue1.length() > 15) {
// if (responseStringArray.length > 1) {
responseStringVal = "\"" + optionValue1.substring(0, 14) + "...\"";
} else {
responseStringVal = "\"" + optionValue1 + "\"";
}
responseStringValues = responseStringValues + "" + responseStringVal + ",";
// legendString=legendString+"<span class='dot' style='background-color:"+
// customColors[i % customColors.length]+"'></span><span
// style='margin-left:10px;margin-left:3px;'>"+ optionValue +"</span>";
i++;
}
}
} else {
// No records
}
cMap.put("responseStringValues", responseStringValues);
cMap.put("dailyResponseCounts", dailyResponseCounts);
cMap.put("responseStringValuesForTable", responseStringValuesForTable);
cMap.put("tableHTML", tableHTML);
return cMap;
}
public static String getChartHTMLString(String projectName, String questionnaireName, String questionId,
String questionValue, String chartType) throws Exception {
String retVal = "";
String dailyResponseCounts = "[";
String responseStringValues = "[";
String responseStringValuesForTable = "[";
String questionnaireJsonDB = "";
JsonArray optionsArray = new JsonArray();
String sql = "Select questionnairedetails from questionnairedetails where projectname='" + projectName
+ "' and questionnairename='" + questionnaireName + "'";
// Get the questionnaire JSON for this entry.
questionnaireJsonDB = new ConnectionFactory().getString(sql);
HashMap<String, String> dataValues = getChartData(projectName, questionnaireName, questionId, questionValue);
if (!StringUtils.trimEndingComma(dataValues.get("dailyResponseCounts")).equals("")) {
dailyResponseCounts = dailyResponseCounts
+ StringUtils.trimEndingComma(dataValues.get("dailyResponseCounts")) + "]";
responseStringValues = responseStringValues
+ StringUtils.trimEndingComma(dataValues.get("responseStringValues")) + "]";
responseStringValuesForTable = responseStringValuesForTable
+ StringUtils.trimEndingComma(dataValues.get("responseStringValuesForTable")) + "]";
// Constant strings across chart types.
String cToolbar = "toolbar: {show: true,offsetX: 0,offsetY: 0,tools: { download: true,selection: true,zoom: true,zoomin: true,zoomout: true, pan: true,customIcons: []}},";
String cFill = "fill: {colors: customColors},";
String cColors = "colors: customColors,";
String cLegend = "legend: {show: true,offsetY: -5,position: 'right',height:'100%'}";
// Only for Pie charts, the series and xaxis fields vary. Hence check and
// continue
if (chartType.equals("pie")) {
retVal = "\n" + "<script> var " + questionId + "_options = {" + " series: "
+ dailyResponseCounts + "," + " chart: { width: 480,height: 550,"
+ " type: '" + chartType + "'," + " data: "
+ dailyResponseCounts + "," + cToolbar +
" events: {"
+ " dataPointMouseEnter: function(event, chartContext, config) {"
+ " highlightRowfunc(chartContext.el.id, config.dataPointIndex,1);"
+ " },"
+ " dataPointMouseLeave: function(event,chartContext,config){"
+ " highlightRowfunc(chartContext.el.id, config.dataPointIndex,0);"
+ " }" + " }" + " }," + cColors
+ " labels: " + responseStringValues + "," + cLegend + " };";
} else {
retVal = "\n" + "<script> var " + questionId + "_options = {"
+ " series:[{ name: 'Count'," + " type: '" + chartType
+ "'," + " data:" + dailyResponseCounts + "" + " }],"
+ " chart: { width: 480,height: 550," + " type: '"
+ chartType + "'," + " data: " + dailyResponseCounts + ","
+ " xaxis: {categories:" + responseStringValues + ",}, " + cToolbar
+ " events: {"
+ " dataPointMouseEnter: function(event, chartContext, config) {"
+ " highlightRowfunc(chartContext.el.id, config.dataPointIndex,1);"
+ " },"
+ " dataPointMouseLeave: function(event,chartContext,config){"
+ " highlightRowfunc(chartContext.el.id, config.dataPointIndex,0);"
+ " }" + " }" + " }," + cFill
+ cColors + " tooltip: {intersect: true,shared: false}, markers: {size: 4},"
+ " labels: " + responseStringValues + "," + cLegend + " };";
}
// Render the chart
retVal = retVal + "var " + questionId + "_chart = new ApexCharts(document.querySelector(\"#" + questionId
+ "_piechart\")," + questionId + "_options);" + questionId + "_chart.render();";
// Render the table content
retVal = retVal + " document.getElementById('table_" + questionId + "').innerHTML=\""
+ dataValues.get("tableHTML") + "\"\n";
// Render the Legend
// if (chartType.equals("pie")) {
// retVal = retVal + "document.getElementById('legend_" + questionId +
// "').innerHTML=\""+ legendString+"\"\n";
// }
retVal = retVal + "" + "" + "" + "</script>";
// retVal = retVal + legendString;
} else {// Return No records Found
retVal = "<script> document.getElementById('table_" + questionId
+ "').innerHTML='<TR><TH>No Records Found</TH></TR>'\n" + "document.getElementById('legend_"
+ questionId + "').innerHTML=\"\"\n </script>";
}
return retVal;
}
public static String getCrossTabChartHTMLString(String projectName, String questionnaireName, String questionId,
String questionValue, String crossTabQuestionValue, boolean stackedStyle) throws Exception {
String retVal = "";
String sql = " SELECT A.surveydetailsid as id, A.response as question1, B.response as question2, count(*) as count FROM surveyresponsedetails "
+ " as A Right Join surveyresponsedetails As B on A.surveydetailsid = B.surveydetailsid"
+ " where A.isduplicate is null and A.surveydetailsid in ("
+ " select generalkey from surveydetails where questionnaireid in ("
+ " select generalkey from questionnairedetails where projectname='" + projectName
+ "' and questionnairename='" + questionnaireName + "')" + " ) and A.question like '"
+ StringEscapeUtils.escapeSql(org.apache.commons.lang3.StringEscapeUtils.unescapeHtml4(questionValue))
+ "'" + " and B.question like '"
+ StringEscapeUtils.escapeSql(
org.apache.commons.lang3.StringEscapeUtils.unescapeHtml4(crossTabQuestionValue))
+ "'"
+ " and A.response is not null and A.response <> '' group by A.response, B.response order by A.response asc;";
String legendString = "";
String tableHTML = "";
// Constant Strings of the Chart Settings
String chartPart1 = "chart: { width:800, type: 'bar',stacked: true,";
String chartPart2 = "stackType: '100%',";
String chartPart3 = "toolbar: { show: true }, },";
String chart = "";
// If the stackedStyle is set to true, then display the chart with percentages.
// else with absolute numbers.
if (stackedStyle) {
chart = chartPart1 + chartPart2 + chartPart3;
} else {
chart = chartPart1 + chartPart2 + chartPart3;
}
String responsive = "responsive: [{ breakpoint: 480, options: { legend: { position: 'bottom', offsetX: -10, offsetY: 0}}}],";
String plotOptions = "plotOptions: {bar: {borderRadius: 8,horizontal: false, },},";
String legendNFill = "legend: {position: 'bottom',offsetX: 40},fill: {opacity: 1} ";
String xaxis = "xaxis: {categories:[";
// Create the series String. This is provide the data for the chart.
String series = "[";
List<Map<String, String>> recordsa = new ConnectionFactory().getArrayForSqlForCrossTab(sql);
System.out.println(recordsa);
if (recordsa.size() > 0) { // Check if any records are returned from the DB.
tableHTML = "<TR><TH>" + questionValue + "</TH><TH>" + crossTabQuestionValue + "</TH><TH>Count</TH></TR>";
// Get the unique options for Question1 and Question2
List<String> listQuestion1 = new ArrayList<String>(); // question1 containing duplicates options
List<String> listQuestion2 = new ArrayList<String>(); // question2 containing duplicates options
List<String> listQuestion3 = new ArrayList<String>(); // question3 containing duplicates options for legends
List<String> listQuestion4 = new ArrayList<String>(); // question4 containing duplicates options for legends
for (Map<String, String> record : recordsa) {
String question1Response = StringEscapeUtils.escapeJava(record.get("question1"));
String question1Response1 = record.get("question1");
for(char c: question1Response1.toCharArray()) {
if(c > 127) {
int sIndex = question1Response1.indexOf(c);
//System.out.println(sIndex);
String replaced = question1Response1.substring(sIndex);
question1Response1 = question1Response1.replace(replaced, "");
System.out.println(question1Response1);
break;
}
}
String question2Response = StringEscapeUtils.escapeJava(record.get("question2"));
String question2Response1 = record.get("question2");
System.out.println(question2Response1);
for(char c: question2Response1.toCharArray()) {
if(c > 127) {
int sIndex = question2Response1.indexOf(c);
System.out.println(sIndex);
String replaced = question2Response1.substring(sIndex);
question2Response1 = question2Response1.replace(replaced, "");
System.out.println(question2Response1);
break;
}
}
listQuestion1.add(question1Response);
//System.out.println(listQuestion1);
listQuestion2.add(question2Response);
listQuestion3.add(question1Response1);
listQuestion4.add(question2Response1);
tableHTML = tableHTML + "<TR><TD>" + question1Response1 + "</TD><TD>" + question2Response1 + "</TD><TD>"
+ record.get("count") + "</TD></TR>";
}
Set<String> setQuestion1 = new HashSet<String>(listQuestion1);
Set<String> setQuestion2 = new HashSet<String>(listQuestion2);
listQuestion1.clear();
listQuestion1.addAll(setQuestion1);
for (String qString : setQuestion2) {
// Initialize the temporary series count list.
List<String> seriesCount = new ArrayList<String>(listQuestion1.size());
for (int y = 0; y < listQuestion1.size(); y++) {
seriesCount.add("");
}
series = series + "{name: '" + qString + "', data: ";
for (Map<String, String> record : recordsa) {
String countString = record.get("count");
String questionString = StringEscapeUtils.escapeJava(record.get("question1"));
String crossTabquestionString = StringEscapeUtils.escapeJava(record.get("question2"));
if (qString.equals(crossTabquestionString)) {
seriesCount.set(listQuestion1.indexOf(questionString), countString);
}
}
for (int t = 0; t < listQuestion1.size(); t++) {
if (seriesCount.get(t) == null || seriesCount.get(t).equals("")) {
seriesCount.set(t, "0");
}
}
series = series + seriesCount.toString() + "},";
}
series = StringUtils.trimEndingComma(series) + "]";
String xAxisLegend = "";
for (int t = 0; t < listQuestion1.size(); t++) {
xAxisLegend = xAxisLegend + "'" + listQuestion1.get(t) + "',";
}
xaxis = xaxis + StringUtils.trimEndingComma(xAxisLegend) + "]},";
// return only stacked Bar graph
retVal = "\n" + "<script> var " + questionId + "_options = {" + " series: " + series + ","
+ chart + responsive + plotOptions + xaxis + legendNFill + " }; ";
// Render the chart
retVal = retVal + "var " + questionId + "_chart = new ApexCharts(document.querySelector(\"#" + questionId
+ "_piechart\")," + questionId + "_options);" + questionId + "_chart.render();";
// Render the table content
retVal = retVal + " document.getElementById('table_" + questionId + "').innerHTML=\"" + tableHTML + "\"\n";
// Render the Legend
retVal = retVal + "document.getElementById('legend_" + questionId + "').innerHTML=\"" + legendString
+ "\"\n";
retVal = retVal + "" + "" + "" + "</script>";
// retVal = retVal + legendString;
} else {// Return No records Found
retVal = "<script> document.getElementById('table_" + questionId
+ "').innerHTML='<TR><TH>No Records Found</TH></TR>'\n" + "document.getElementById('legend_"
+ questionId + "').innerHTML=\"\"\n </script>";
}
return retVal;
}
}

How to convert string to json sequentially

public void addNewUser(MongoClient mdbClient, String newUserName, String newUserPassword, DBManagement.DBRole roles) {
System.out.println("inside addNEw User method");
Map<String, String> user = new LinkedHashMap<String, String>();
user.put("createUser", newUserName);
user.put("pwd", newUserPassword);
List<Map<String, String>> listOfRoles = new ArrayList<Map<String, String>>();
Map<String, String> role1 = new LinkedHashMap<String, String>();
role1.put("role",roles.getRole());
role1.put("db", roles.getDb());
listOfRoles.add(role1);
user.put("roles", listOfRoles.toString());
System.out.println("MAP: " + user);
try{
String json = new ObjectMapper().writeValueAsString(user);
/*String json = new ObjectMapper().convertValue(user);*/
System.out.println(json);
//String jsonCommand = "{ createUser: \" + newUserName +"/" + " ," + "pwd: /" + newUserPassword + "/" + " ," + "roles : [" + roles_str + "]}" ;
String jsonCommand = json;
System.out.println("createUserString-->"+jsonCommand);
Document command = new Document(Document.parse(jsonCommand));
Document collStatsResults = mdbClient.getDatabase("admin").runCommand(command);
System.out.println(collStatsResults.toJson());
} catch(Exception e) {
System.out.println("Error " + e);
}
}
I am getting output string as -{"createUser":"demoUser2","pwd":"password","roles":"[{role=dbOwner, db=udata}]"}
Expected output- {"createUser":"demoUser2","pwd":"password","roles":[{"role":"dbOwner", "db":"udata"}]}
Firstly i used JSONObject() but it doesnt care about the json sequence ,so i tried with linkedhashMap but facing array conversion issue..can anyone help.Or is there any other way to generate json sequentially.

replace substring from string in java

I have the string hello Mr $name ur score is $value, What is the best way to get $name and $value part?
String json = "{\n" + "\"id\": 1,\n" + "\"data\":[\n" + "{\n"
+ "\"to\":123456789,\"name\":\"james\",\"value\":200\n" + "},\n" + "{\n"
+ "\"to\":123456789,\"name\":\"jhon\",\"value\":20\n" + "}]\n" + "}\n" + "";
Object obj = new JSONParser().parse(json);
JSONObject jsonObject = (JSONObject) obj;
long id = (long) jsonObject.get("id");
JSONArray arrayOfdata = (JSONArray) jsonObject.get("data");
JSONObject dataObject = new JSONObject();
ArrayList<String> data = new ArrayList<>();
for (String w : words) {
if (w.contains("$"))
if (json.contains(w.substring(1))) {
data.add(w.substring(1));
}
}
for (int n = 0; n < arrayOfdata.size(); n++) {
dataObject = (JSONObject) arrayOfdata.get(n);
for (int j = 0; j < data.size(); j++) {
String msg = message.replace(data.get(j).toString(), dataObject.get(data.get(j)).toString());
String strNew = msg.replace("$", "");
logger.info("strNew " + strNew);
}
}
Result
public static void main(String...strings) {
String inputString = "{\n" + "\"id\": 1,\n" + "\"data\":[\n" + "{\n" + "\"to\":123456789,\"name\":\"james\",\"value\":200\n" + "},\n" + "{\n" + "\"to\":123456789,\"name\":\"jhon\",\"value\":20\n" + "}]\n" + "}\n" + "";
Pattern pattern = Pattern.compile("(?:\"name\":\")(.*?)(?:\"value\":)[0-9]*");
Matcher m = pattern.matcher(inputString);
while (m.find()) {
String[] matches = m.group().split(",");
String name = null, value = null;
for (String match : matches) {
if(match.contains("name")){
name= match.substring(match.indexOf("name")+"name".length()).replaceAll("\"", "");
}else if(match.contains("value")) {
value= match.substring(match.indexOf("value")+"value".length()).replaceAll("\"", "");
}
}
System.out.println("Bonjour Mr. "+name+" votre score est value "+value);
}
}
I kind of understand the aim of your code, here is an attempt to get for each entry in the json array, the name and the values of each, I hope it helps.
String json = "{\n" + "\"id\": 1,\n" + "\"data\":[\n" + "{\n"
+ "\"to\":123456789,\"name\":\"james\",\"value\":200\n" + "},\n" + "{\n"
+ "\"to\":123456789,\"name\":\"jhon\",\"value\":20\n" + "}]\n" + "}\n" + "";
JSONObject jsonObject = new JSONObject(json);
JSONArray arrayOfdata = (JSONArray) jsonObject.get("data");
String message = "hello Mr %s your score is %s";
for (int i = 0; i < arrayOfdata.length(); i++) {
JSONObject obj = arrayOfdata.getJSONObject(i);
Object name = obj.get("name");
Object value = obj.get("value");
System.out.printf(message, name, value);
System.out.println();
}

Check last element of hash map

I want to use a function for the update operation. So to create SQL query I must make sure the last element does not get coma(,)
I tried this
public Boolean updateSingleClient(Map map, String id) {
String updateSet = "";
int count = 0;
for (Object key : map.keySet()) {
String value = (String) map.get(key);
System.out.println("Count is " + count);
count = count + 1;
if (count == map.size()) {
updateSet = updateSet + key + "='" + value + "'";
} else {
updateSet = updateSet + key + "='" + value + "',";
}
}
System.out.println(updateSet);
return false;
}
Is there any way to check if this is the last element of HashMap?
Because this code is not working fine for me.
The last element in the iteration will be at map.size() - 1, not at map.size().
But note you can save a lot of this boilerplate code by streaming the map in to Collectors.joining:
String result =
map.entrySet()
.stream()
.map(e -> e.getKey() + " = '" + e.getValue() + "'"
.collect(Collectors.joining(","));
You can use a StringBuilder:
Append elments to StringBuilder
Remove last ,
Sample code:
public Boolean updateSingleClient(Map map, String id) {
StringBuilder updateSet = new StringBuilder();
for (Object key : map.keySet()) {
String value = (String) map.get(key);
updateSet.append(key + "='" + value + "',");
}
updateSet.deleteCharAt(updateSet.lastIndexOf(","));
System.out.println(updateSet);
return false;
}

Trouble Updating a Table Row in Java

Connection conn = SqlConnection.getConnection("jdbc:mysql://localhost:3306/stocks");
Statement statement = conn.createStatement();
File path = new File("/Users/Zack/Desktop/JavaDB/BALANCESHEETS");
for(File file: path.listFiles()) {
if (file.isFile()) {
String fileName = file.getName();
String ticker = fileName.split("\\_")[0];
if (ticker.equals("ASB") || ticker.equals("FRC")) {
if (ticker.equals("ASB")) {
ticker = ticker + "PRD";
}
if (ticker.equals("FRC")) {
ticker = ticker + "PRD";
}
}
//CSVReader reader = new CSVReader(new FileReader(file));
//List entries = reader.readAll();
//ArrayList<String> entry = new ArrayList<String>();
Reader reader = new BufferedReader(new FileReader(file));
StringBuilder builder = new StringBuilder();
int c;
while ((c = reader.read()) != -1) {
builder.append((char) c);
}
String string = builder.toString();
ArrayList<String> stringResult = new ArrayList<String>();
if (string != null) {
String[] splitData = string.split("\\s*,\\s*|\\n");
for (int i = 0; i <splitData.length; i++) {
if (!(splitData[i] == null) || !(splitData[i].length() ==0)) {
stringResult.add(splitData[i].trim());
}
}
}
String columnName = null;
int yearCount = 0;
for (int i = 0; i < stringResult.size(); i++) {
int sL = stringResult.get(i).length();
for (int x = 0; x < sL; x++) {
if (Character.isLetter(stringResult.get(i).charAt(x))) {
yearCount = 0;
System.out.println("index: " + i);
columnName = stringResult.get(i);
columnName = columnName.replace(" ", "_");
System.out.println(columnName);
i++;
break;
}
}
yearCount++;
String value = stringResult.get(i);
System.out.println("Year: " + stringResult.get(yearCount) + " Value: " + value + " Stock: " + ticker + " Column: " + columnName );
if (!(columnName == null)) {
String writeValues = "INSERT INTO BalanceSheet (ticker, Year, " + columnName + ") "
+ "VALUE ('" + ticker + "','" + stringResult.get(yearCount) + "','" + value + "')";
String writeValues2 = "UPDATE BalanceSheet "
+ "SET ticker = '" + ticker + "', "
+ "Year = '" + stringResult.get(yearCount) + "', "
+ columnName + " = '" + value + "' "
+ "WHERE ticker = '" + ticker + "'";
statement.executeUpdate(writeValues2);
}
}
Towards the bottom of the code are two queries I tried, I'm trying to get all data organized by ticker and year into a table, "writeColumns" works but it's making a new row for every new "value" put into "columnName". My second attempt "writeColumns2" doesn't do anything.
I want to update the same row with a certain year for all values and then move onto the next year, then next ticker.
If I have understood your question correctly, you want to insert a row if it doesn't exists but update the values if it already does. You need to use ON DUPLICATE KEY UPDATE
String writeValues = "INSERT INTO BalanceSheet (ticker, Year, " + columnName + ") "
+ "VALUES (?,?,?) "
+"ON DUPLICATE KEY UPDATE " + columnName +"=?";
Statement statement = conn.prepareStatement(writeValues);
statement.setString(1,ticker);
statement.setString(2,stringResult.get(yearCount));
statement.setString(3, value);
This will solve your immidiate problem provided you create a UNIQUE index on ticker,year
However there are lot's of other issues here.
An update for each column - Currently you are doing an insert/update for each column on the table. What you are supposed to do is to insert update all the columns at one.
You are not using prepared statements addressed in my code sample
You shouldn't be doing this at all the best way to batch process data is to use MYSQL's built in LOAD DATA INFILE command. If your data is not in a format that can be easily imported into mysql, what your Java code can do is to transform it into a format that can be. Such a code will be a lot simpler and neater than what you have now

Categories