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();
}
Related
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;
}
}
I am trying to parse the below json but unable to do that as stack over flow error comes in.
Here is the JSON -
[{
"Class": "1",
"school": "test",
"description": "test",
"student": [
"Student1",
"Student2"
],
"qualify": true,
"annualFee": 3.00
}]
Here is the code which is failing currently.
String res = cspResponse.prettyPrint();
org.json.JSONObject obj = new org.json.JSONObject(res);
org.json.JSONArray arr = obj.getJSONArray(arrayName);
String dataStatus=null;
for (int i = 0; i < arr.length(); i++) {
dataStatus = arr.getJSONObject(i).getString(key);
System.out.println("dataStatus is \t" + dataStatus);
}
Usecases are:
To get the value key "class"
Get the value from Student
Get the value from school
I appreciate your help.
update-1
Code more info on stack trace updated with below details.
cls = 1
error- org.json.JSONException: JSONObject["student "] not a string.
Stack trace-
public String getString(String key) throws JSONException {
Object object = this.get(key);
if (object instanceof String) {
return (String) object;
}
throw new JSONException("JSONObject[" + quote(key) + "] not a string.");
}
When I ran the code with the below answers, here its failing for student is not a string.
The answers I used from first two comments and both have the same error. I appropriate your help.
Your json fragment is invalid - the last comma breaks the parsing. But the rest of the code is quite workable.
String res = "[\n" +
" {\n" +
" \"Class\": \"1\",\n" +
" \"school\": \"test\",\n" +
" \"description\": \"test\",\n" +
" \"student\": [\n" +
" \"Student1\",\n" +
" \"Student2\"\n" +
" ],\n" +
" \"qualify\": true,\n" +
" \"annualFee\": 3.00\n" +
" }\n" +
"]";
JSONArray arr = new JSONArray(res);
for (int i = 0; i < arr.length(); i++) {
JSONObject block = arr.getJSONObject(i);
Integer cls = block.getInt("Class");
System.out.println("cls = " + cls);
Object school = block.getString("school");
System.out.println("school = " + school);
JSONArray students = block.getJSONArray("student");
System.out.println("student[0] = " + students.get(0));
System.out.println("student[1] = " + students.get(1));
}
should output
cls = 1
school = test
student[0] = Student1
student[1] = Student2
Your JSON reponse root is array but you consider your JSON response as JSON object
Changing your parsing json code as below
String res=cspResponse.prettyPrint();
org.json.JSONArray arr = new org.json.JSONArray(res);
String dataStatus=null;
for (int i = 0; i < arr.length(); i++) {
org.json.JSONObject obj=arr.getJSONObject(i);
dataStatus = obj.getString(key);
System.out.println("dataStatus is \t" + dataStatus);
String schoolName = org.getString("school");
System.out.println("school => " + schoolName);
org.json.JSONArray students = obj.getJSONArray("student");
System.out.println("student[0] = " + students.get(0));
System.out.println("student[1] = " + students.get(1));
}
You can use simple JSONObject class and Simple JSONParser for parsing the JSON.
1. Parse the JSON.
org.json.simple.JSONParser parser = new org.json.simple.JSONParser();
org.json.simple.JSONObject parsedJSON = parser.parse(inputJSON);
2. To get class:
String class = parsedJSON.get("Class");
3. To get Students:
org.json.simple.JSONArray studentArray = parsedJSON.get("student");
4. To Get School:
String school = parsedJSON.get("school");
After the above steps, you can run a for-loop to print the class and students.
[
"label": {
"originalName" : "Case #",
"modifiedLabel" : "Case #",
"labelId" : "case_number_lbl",
"isEditable" : "true",
"imageClass" : ""
}
]
In the above Json Array I need to replace "Case #" with "Ticket #". This is occuring in somany places. Any one update please.
Thanks In advance.
I think a simple loop should solve your problem:
public static void main(String[] args) throws JSONException {
JSONArray array = new JSONArray("[" +
" {" +
" originalName : \"Case #\"," +
" modifiedLabel : \"Case #\"," +
" labelId : \"case_number_lbl\"," +
" isEditable : \"true\"," +
" imageClass : \"\"" +
" }" +
"]");
System.out.println(array.toString(2));
for (int i = 0; i < array.length(); i++) {
JSONObject object = array.getJSONObject(i);
JSONArray keys = object.names();
for (int j = 0; j < keys.length(); j++) {
String key = keys.getString(j);
if (object.getString(key).equals("Case #")) {
object.put(key, "Ticket #");
}
}
}
System.out.println();
System.out.println(array.toString(2));
}
You can use GSON to convert your json to java Object and then you can change your string .
You can exchange the value with the help String.replaceAll()
String jSONString = ...; // Your JSon string
String newString = jSONString.replace("Case #", "Ticket #");
ANDROID
I am getting the below response in my WSDL API:
a:10:{s:11:"sso_user_id";s:6:"123345";s:9:"firstname";s:0:"";s:8:"lastname";s:0:"";s:5:"abono";s:0:"";s:4:"hash";s:32:"c2ff5bc4598d02160b57e2b3f28a3e0e";s:5:"token";s:32:"2da9ba3bcc52fdb047c3da5d91e3cdbd";s:5:"login";s:23:"sandor.fekete#inform.hu";s:6:"cookie";s:232:"";s:6:"access";a:1:{s:4:"role";s:2:"NO";}s:5:"error";s:0:"";}
I have taken the String between response tag,
Now here is info about the response structure:
s:11:"sso_user_id";-
sso_user_id is the key having the length of 11 character.
s:6:"123345";- 123345 is the value of sso_user_id having length of 6 character.
Now can anybody help me to PARSE or FORMAT or give REGEXP to make the normal String or easily understandable String.
NOTE:- THIS IS NOT A JSON STRING.
IOS code and logic also most welcome.
I have managed to do this:
public static void parseSOAPPrimitiveObject(String input, Object output)
throws NumberFormatException, IllegalArgumentException,
IllegalAccessException, InstantiationException {
Class theClass = output.getClass();
Field[] fields = theClass.getDeclaredFields();
for (int i = 0; i < fields.length; i++) {
Type type = fields[i].getType();
fields[i].setAccessible(true);
// detect String
if (fields[i].getType().equals(String.class)) {
String tag = "" + fields[i].getName() + "";
if (input.contains(tag)) {
String strValue = "";
strValue = input.substring(input.indexOf(tag)
+ tag.length() + 2);
if (getValueLength(strValue) > 0) {
strValue = getValue(strValue);
} else {
strValue = "";
}
fields[i].set(output, strValue);
}
}
// detect int or Integer
if (type.equals(Integer.TYPE) || type.equals(Integer.class)) {
String tag = "" + fields[i].getName() + "";
if (input.contains(tag)) {
String strValue = "";
strValue = input.substring(input.indexOf(tag)
+ tag.length() + 2);
fields[i].set(output, getValueLengthInt(strValue));
}
}
}
}
public static String getValue(String substring) {
String str = new String(substring);
final Pattern pattern = Pattern.compile("\"(.+?)\"");
final Matcher matcher = pattern.matcher(str);
matcher.find();
return matcher.group(0);
}
public static int getValueLength(String substring) {
final Pattern pattern = Pattern.compile(":(.+?):");
final Matcher matcher = pattern.matcher(substring);
matcher.find();
int count = 0;
count = Integer.parseInt(matcher.group(1));
return count;
}
public static int getValueLengthInt(String substring) {
final Pattern pattern = Pattern.compile(":(.+?);");
final Matcher matcher = pattern.matcher(substring);
matcher.find();
int count = 0;
count = Integer.parseInt(matcher.group(1));
return count;
}
Class for Object:
public class SSOuser {
String sso_user_id;
String firstname;
String lastname;
String abono;
String hash;
String token;
String login;
String cookie;
String role;
String error;
}
To show Data:
SSOuser ouser = getFormatedResponseData(result.toString());
String finalValues = "";
finalValues = finalValues + "\n" + "fname= " + ouser.firstname;
finalValues = finalValues + "\n" + "lastname= " + ouser.lastname;
finalValues = finalValues + "\n" + "abono= " + ouser.abono;
finalValues = finalValues + "\n" + "hash= " + ouser.hash;
finalValues = finalValues + "\n" + "role= " + ouser.role;
finalValues = finalValues + "\n" + "sso_user_id= " + ouser.sso_user_id;
finalValues = finalValues + "\n" + "token= " + ouser.token;
finalValues = finalValues + "\n" + "login= " + ouser.login;
finalValues = finalValues + "\n" + "error= " + ouser.error;
// finalValues=finalValues+
// "\n"+"cookie= " + output.cookie;
final String val = finalValues;
runOnUiThread(new Runnable() {
public void run() {
txtValues.setText(val);}});
I am trying to parse a JSON string in java to have the individual value printed separately. But while making the program run I get the following error-
Exception in thread "main" java.lang.RuntimeException: Stub!
at org.json.JSONObject.<init>(JSONObject.java:7)
at ShowActivity.main(ShowActivity.java:29)
My Class looks like-
import org.json.JSONException;
import org.json.JSONObject;
public class ShowActivity {
private final static String jString = "{"
+ " \"geodata\": ["
+ " {"
+ " \"id\": \"1\","
+ " \"name\": \"Julie Sherman\","
+ " \"gender\" : \"female\","
+ " \"latitude\" : \"37.33774833333334\","
+ " \"longitude\" : \"-121.88670166666667\""
+ " }"
+ " },"
+ " {"
+ " \"id\": \"2\","
+ " \"name\": \"Johnny Depp\","
+ " \"gender\" : \"male\","
+ " \"latitude\" : \"37.336453\","
+ " \"longitude\" : \"-121.884985\""
+ " }"
+ " }"
+ " ]"
+ "}";
private static JSONObject jObject = null;
public static void main(String[] args) throws JSONException {
jObject = new JSONObject(jString);
JSONObject geoObject = jObject.getJSONObject("geodata");
String geoId = geoObject.getString("id");
System.out.println(geoId);
String name = geoObject.getString("name");
System.out.println(name);
String gender=geoObject.getString("gender");
System.out.println(gender);
String lat=geoObject.getString("latitude");
System.out.println(lat);
String longit =geoObject.getString("longitude");
System.out.println(longit);
}
}
Let me know what is it I am missing, or the reason why I do get that error everytime I run the application. Any comments would be appreciated.
See my comment.
You need to include the full org.json library when running as android.jar only contains stubs to compile against.
In addition, you must remove the two instances of extra } in your JSON data following longitude.
private final static String JSON_DATA =
"{"
+ " \"geodata\": ["
+ " {"
+ " \"id\": \"1\","
+ " \"name\": \"Julie Sherman\","
+ " \"gender\" : \"female\","
+ " \"latitude\" : \"37.33774833333334\","
+ " \"longitude\" : \"-121.88670166666667\""
+ " },"
+ " {"
+ " \"id\": \"2\","
+ " \"name\": \"Johnny Depp\","
+ " \"gender\" : \"male\","
+ " \"latitude\" : \"37.336453\","
+ " \"longitude\" : \"-121.884985\""
+ " }"
+ " ]"
+ "}";
Apart from that, geodata is in fact not a JSONObject but a JSONArray.
Here is the fully working and tested corrected code:
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
public class ShowActivity {
private final static String JSON_DATA =
"{"
+ " \"geodata\": ["
+ " {"
+ " \"id\": \"1\","
+ " \"name\": \"Julie Sherman\","
+ " \"gender\" : \"female\","
+ " \"latitude\" : \"37.33774833333334\","
+ " \"longitude\" : \"-121.88670166666667\""
+ " },"
+ " {"
+ " \"id\": \"2\","
+ " \"name\": \"Johnny Depp\","
+ " \"gender\" : \"male\","
+ " \"latitude\" : \"37.336453\","
+ " \"longitude\" : \"-121.884985\""
+ " }"
+ " ]"
+ "}";
public static void main(final String[] argv) throws JSONException {
final JSONObject obj = new JSONObject(JSON_DATA);
final JSONArray geodata = obj.getJSONArray("geodata");
final int n = geodata.length();
for (int i = 0; i < n; ++i) {
final JSONObject person = geodata.getJSONObject(i);
System.out.println(person.getInt("id"));
System.out.println(person.getString("name"));
System.out.println(person.getString("gender"));
System.out.println(person.getDouble("latitude"));
System.out.println(person.getDouble("longitude"));
}
}
}
Here's the output:
C:\dev\scrap>java -cp json.jar;. ShowActivity
1
Julie Sherman
female
37.33774833333334
-121.88670166666667
2
Johnny Depp
male
37.336453
-121.884985
To convert your JSON string to hashmap you can make use of this :
HashMap<String, Object> hashMap = new HashMap<>(Utility.jsonToMap(response)) ;
Use this class :) (handles even lists , nested lists and json)
public class Utility {
public static Map<String, Object> jsonToMap(Object json) throws JSONException {
if(json instanceof JSONObject)
return _jsonToMap_((JSONObject)json) ;
else if (json instanceof String)
{
JSONObject jsonObject = new JSONObject((String)json) ;
return _jsonToMap_(jsonObject) ;
}
return null ;
}
private static Map<String, Object> _jsonToMap_(JSONObject json) throws JSONException {
Map<String, Object> retMap = new HashMap<String, Object>();
if(json != JSONObject.NULL) {
retMap = toMap(json);
}
return retMap;
}
private static Map<String, Object> toMap(JSONObject object) throws JSONException {
Map<String, Object> map = new HashMap<String, Object>();
Iterator<String> keysItr = object.keys();
while(keysItr.hasNext()) {
String key = keysItr.next();
Object value = object.get(key);
if(value instanceof JSONArray) {
value = toList((JSONArray) value);
}
else if(value instanceof JSONObject) {
value = toMap((JSONObject) value);
}
map.put(key, value);
}
return map;
}
public static List<Object> toList(JSONArray array) throws JSONException {
List<Object> list = new ArrayList<Object>();
for(int i = 0; i < array.length(); i++) {
Object value = array.get(i);
if(value instanceof JSONArray) {
value = toList((JSONArray) value);
}
else if(value instanceof JSONObject) {
value = toMap((JSONObject) value);
}
list.add(value);
}
return list;
}
}
credit to this blog
This answer may help someone whose requirements are different.
This is your Json string
{
"pageNumber":20,
"pageTitle":"example page title",
"pageInfo": {
"pageName": "Homepage",
"logo": "https://www.example.com/logo.jpg"
},
"posts": [
{
"post_id": "0123456789",
"actor_id": "1001",
"author_name": "Jane Doe",
"post_title": "How to parse JSON in Java",
"comments": [],
"time_of_post": "1234567890"
}
]
}
and this is how to read it
import org.json.JSONArray;
import org.json.JSONObject;
public class ParseJSON {
static String json = "...";
public static void main(String[] args) {
JSONObject obj = new JSONObject(json);
String pageTitle = obj.getString("pageTitle");
String pageNumber= obj.getInt("pageNumber");
String pageName = obj.getJSONObject("pageInfo").getString("pageName");
System.out.println(pageNumber);
System.out.println(pageTitle );
System.out.println(pageName);
JSONArray arr = obj.getJSONArray("posts");
for (int i = 0; i < arr.length(); i++) {
String post_id = arr.getJSONObject(i).getString("post_id");
System.out.println(post_id);
}
}
}
Looks like for both of your objects (inside the array), you have an extra closing brace after "Longitude".
Firstly there is an extra } after every array object.
Secondly "geodata" is a JSONArray. So instead of JSONObject geoObject = jObject.getJSONObject("geodata"); you have to get it as JSONArray geoObject = jObject.getJSONArray("geodata");
Once you have the JSONArray you can fetch each entry in the JSONArray using geoObject.get(<index>).
I am using org.codehaus.jettison.json.
Here is the example of one Object, For your case you have to use JSONArray.
public static final String JSON_STRING="{\"employee\":{\"name\":\"Sachin\",\"salary\":56000}}";
try{
JSONObject emp=(new JSONObject(JSON_STRING)).getJSONObject("employee");
String empname=emp.getString("name");
int empsalary=emp.getInt("salary");
String str="Employee Name:"+empname+"\n"+"Employee Salary:"+empsalary;
textView1.setText(str);
}catch (Exception e) {e.printStackTrace();}
//Do when JSON has problem.
}
I don't have time but tried to give an idea. If you still can't do it, then I will help.
you have an extra "}" in each object,
you may write the json string like this:
public class ShowActivity {
private final static String jString = "{"
+ " \"geodata\": ["
+ " {"
+ " \"id\": \"1\","
+ " \"name\": \"Julie Sherman\","
+ " \"gender\" : \"female\","
+ " \"latitude\" : \"37.33774833333334\","
+ " \"longitude\" : \"-121.88670166666667\""
+ " }"
+ " },"
+ " {"
+ " \"id\": \"2\","
+ " \"name\": \"Johnny Depp\","
+ " \"gender\" : \"male\","
+ " \"latitude\" : \"37.336453\","
+ " \"longitude\" : \"-121.884985\""
+ " }"
+ " }"
+ " ]"
+ "}";
}