Array inside an array using JSON - java

This is code in JAVA I used JSONArray and method JSONarray.put(string);
public JSONArray getChart() {
Connection con = getConnectionObject();
Statement st = null;
ResultSet rs = null;
JSONObject jCharto = new JSONObject();
JSONArray arr = new JSONArray();
try {
st = con.createStatement();
String query = "select count(books_issued) as books_issued,command from fact_aaglib, school where fact_aaglib.school_name = school.school_name group by command;";
rs = st.executeQuery(query);
System.out.println("['Command','Book Issued'],");
while (rs.next())
{
String zone = rs.getString("command");
arr.put(zone);
int booksissued = rs.getInt("books_issued");
arr.put(booksissued);
}
System.out.println(arr+",");
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (con != null)
con.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
return arr;
}
Here is my output
['Command','Book Issued'],["Central",324,"Southern",312,"South-West",192,"Eastern",264,"Northern",84,"Western",396],
But actual I want output like this:
[
['Command', 'Books Issued'],
["Central",324],["Southern",312],
["South-West",192],
["Eastern",264],
["Northern",84],
["Western",396]
]
And this data is using in google charts to draw bar chart .

A JSONArray is not limited to strings.
You need to create one array for holding records, then create a new one for each pair or records. Here is the basic idea:
// create the "top" array
JSONArray topArray = new JSONArray();
// add your static "headers"
JSONArray headers = new JSONArray();
headers.put("Command");
headers.put("Book Issued");
topArray.put(headers);
while (rs.next()){
// create a new array for the current record
JSONArray recordArray = new JSONArray();
// populate the record array
String zone = rs.getString("command");
recordArray.put(zone);
int booksissued = rs.getInt("books_issued");
recordArray.put(booksissued);
// append the record array to the top array
topArray.put(recordArray);
}
return topArray;

Related

How can I convert Json String to List<HashMap<String, String>>?

I creating compare data A and each data using Java.
First, I did extract array data from txt file (array type in file).
Second, I have a Json String data in my database (MySQL column type : JSON).
I parsed txt file and make List
FileInputStream fstream = new FileInputStream(Path);
List<HashMap<String, String>> list = list(fstream);
public List<HashMap<String, String>> list(FileInputStream fstream) {
BufferedReader buff = new BufferedReader(new InputStreamReader(fstream));
List<HashMap<String, String> list = new ArrayList<>();
try {
while ((strLine = buff.readLine()) != null) {
s = strLine.split(" ");
HashMap<String, String> map = new HashMap<>();
pts = s[4].split(":")[1];
ptstime = s[5].split(":")[1];
map.put("pts", pts);
map.put("ptstime", getDurationString(ptstime));
if (pts_itv.equals("0") && ptstime_itv.equals("00:00")) {
map.put("pts_itv", "0");
map.put("ptstime_itv", "00:00");
}
else {
map.put("pts_itv", String.valueOf(Long.parseLong(pts) - Long.parseLong(pts_itv)));
map.put("ptstime_itv", getDurationString(String.valueOf(String.format("%.4f", Double.parseDouble(ptstime) - Double.parseDouble(ptstime_itv)))));
}
pts_itv = pts;
ptstime_itv = ptstime;
list.add(map);
}
}
catch (IOException ex) {
LOG.error("ERROR : " + ex.getLocalizedMessage() + ", " + ex.getMessage());
}
finally {
try {
buff.close();
} catch (IOException ex) {}
}
return list;
}
Extraction data
[{pts_itv=0, ptstime=00:00:00.112792, pts=2707, ptstime_itv=00:00}, {pts_itv=192192, ptstime=00:00:08.12079, pts=194899, ptstime_itv=00:00:08.80}, {pts_itv=128128, ptstime=00:00:13.4595, pts=323027, ptstime_itv=00:00:05.3387}, {pts_itv=277277, ptstime=00:00:25.127, pts=600304, ptstime_itv=00:00:11.5532}]
I can get index key, object key.
list.get(0).get("pts_itv");
And Second data (SELECT Query from MySQL (Column JSON Type))
rs = Web.getInstance().getList(idx); //get data by sql query
jObj = (JSONObject) new JSONParser().parse(rs);
jArr = (JSONArray) jObj.get("data");
for (int i = 0; i < jArr.size(); i++) {
JSONObject Jarr = (JSONObject) jArr.get(i);
System.out.println(Jarr.get("PtsData"));
}
PtsData is
[{"pts": "81831", "pts_itv": "0", "ptstime": "00:00:03.40963", "ptstime_itv": "00:00"}, {"pts": "127877", "pts_itv": "46046", "ptstime": "00:00:05.32821", "ptstime_itv": "00:00:01.9186"}, {"pts": "157907", "pts_itv": "30030", "ptstime": "00:00:06.57946", "ptstime_itv": "00:00:01.2512"}]
java.lang.String
I want PtsData convert to first data type. How can I convert PtsData to List type?
Here are some suggestions to solve this problem.
Don't use String operations un-till they are really needed, you can avoid split by using JSON library to parse JSON data. More code you write, more bugs you introduce and more maintenance it need.
Use Object modelling. This would be more readable to use it in HashMap. Create an object model by defining peroperties pts, pts_itv, ptstime, ptstime_itv.Then choose your key and value. Define equals and hashcode. Then check equality of objects either with your own way to or use equals.

how to iterate json String

I have an array of JSON strings like:
[{
"id":"BirthDate",
"field":"BirthDate",
"type":"date",
"input":"text",
"operator":"equal",
"value":"2016/04/07"
}]
I want to be able to iterate this array and want to get its id, field, value in Java
Using the below code I got an exception
"json object must begin with {"
String rules=helper.getRules();
System.out.println("====Rulses=====:"+rules);
try {
JSONObject obj = new JSONObject(rules);
System.out.println("====obj===="+obj);
// boolean error = obj.getBoolean("error");
String id = obj.getString("id");
System.out.println("===id is===: "+id);
} catch (JSONException e){
e.printStackTrace();
}
You should instead create a JSONArray from the String and then iterate over the array. Modify your code as
String rules=helper.getRules();
System.out.println("====Rulses=====:"+rules);
try {
// create the json array from String rules
JSONArray jsonRules = new JSONArray(rules);
// iterate over the rules
for (int i=0; i<jsonRules.length();i++){
JSONObject obj = jsonRules.get(i);
System.out.println("====obj===="+obj);
String id = obj.getString("id");
System.out.println("===id is===: "+id);
}
} catch (JSONException e){
e.printStackTrace();
}
Try this parsing your rulesinto a JSONArray:
String rules = "[{\"id\":\"BirthDate\",\"field\":\"BirthDate\",\"type\":\"date\",\"input\":\"text\",\"operator\":\"equal\",\"value\":\"2016/04/07\"}]";
try {
JSONArray obj = new JSONArray(rules); // parse the array
for(int i = 0; i < obj.length(); i++){ // iterate over the array
JSONObject o = obj.getJSONObject(i);
String id = o.getString("id");
System.out.println("===id is===: " + id);
}
} catch (JSONException e){
e.printStackTrace();
}
In the JSON you gave as example you just have one element in your array.

Get the JSONObject in the right order

I am using org.json library and am trying to create JSON Object stops in the simple form as below but I am always getting all timeEntries in the same JSONArray timeArray and the name is always changes in the stops as in the current output
Current output:
{"arrival_time":
{"mon-fri":[
["04:48","05:18","05:46","06:16"],
["04:52","05:22","05:50","06:20"],
["04:57","05:27","05:56","06:26"]
]
},
"stops_name":"third name"}
Code:
ArrayList<String> result = new ArrayList<String>();
JSONObject stops = new JSONObject();
JSONObject arrivals = new JSONObject();
JSONArray arrivalMoFr = new JSONArray();
for (Entry<String, List<String>> entry : map.entrySet()) {
String name = entry.getKey();
List<String> timeEntries = entry.getValue();
try {
stops.put("stops_name", name);
JSONArray timeArray = new JSONArray(timeEntries);
arrivalMoFr.put( timeArray);
arrivals.put("mon-fri", arrivalMoFr);
stops.put("arrival_time", arrivals);
System.out.println(stops.toString(3));
} catch (JSONException e) {
e.printStackTrace();
}
Simple how should the result like
{"arrival_time":
{"mon-fri":["04:48","05:18","05:46","06:16"]
}
"stops_name":"first name"},
{"arrival_time":
{"mon-fri":["04:52","05:22","05:50","06:20"]
}
"stops_name":"second name"},
{"arrival_time":
{"mon-fri":["04:57","05:27", "05:56","06:26"]
}
"stops_name":"third name"}
Keep in mind that you want an array as your root object. You'll have to create the other array and objects multiple times, so initializing them outside the for loop isn't useful.
ArrayList<String> result = new ArrayList<String>();
JSONArray stops = new JSONArray();
for (Entry<String, List<String>> entry : map.entrySet()) {
String name = entry.getKey();
List<String> timeEntries = entry.getValue();
try {
JSONObject stop = new JSONObject();
stop.put("stops_name", name);
JSONArray timeArray = new JSONArray(timeEntries);
//arrivalMoFr.put( timeArray);
JSONObject arrivals = new JSONObject();
arrivals.put("mon-fri", timeArray);
stop.put("arrival_time", arrivals);
stops.put(stop);
//System.out.println(stops.toString(3));
} catch (JSONException e) {
e.printStackTrace();
}
}

How to put JSONArray of object in JSONObject inside servlet

I am trying to populate multiple selectbox dynamically using $.ajax() method....
Here is my html code......
<select id="imageSize" name="ImageSizeId"></select>
<select id="circulation" name="circulationId"></select>
Here is my servlet code.....
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/json;charset=utf-8");
response.setHeader("Cache-Control", "no-cache");
PrintWriter out = response.getWriter();
JSONObject usesfactors = new JSONObject();
JSONArray jArraysize = new JSONArray();
JSONArray jArraycirculation = new JSONArray();
Statement stmtsize,stmtcirculation;
ResultSet rssize,rscirculation;
int category_id = Integer.parseInt(request.getParameter("CategoryId"));
int format_id = Integer.parseInt(request.getParameter("FormatId"));
String size,display,des;
int sizeid;
try {
if(category_id == 2 && format_id == 201){
// Get image size factors
String sql1="SELECT SizeId,Size FROM Size WHERE Category_id = "+category_id+" AND Format_id = "+format_id+" ";
PreparedStatement ps1 = conn.prepareStatement(sql1);
rssize = ps1.executeQuery() ;
if( rssize!=null){
System.out.println("Not Null");// its printing even if resultset rssize has no records.......why?
while(rssize.next())
{
System.out.println("inside resultset");
JSONObject jobj = new JSONObject();
sizeid = rssize.getInt("SizeId");
size=rssize.getString("Size");
System.out.println(size);
jobj.put("SizeId", sizeid);
jobj.put("Size", size);
jArraysize.add(jobj);
}
usesfactors.put("Size", jArraysize);
rssize.close();
}
else{
System.out.println("Does not have Size factors");
}
// Get image circulation factors
String sql2="SELECT circulationId,circulation FROM Circulation WHERE Category_id = "+category_id+" AND Format_id = "+format_id+" ";
PreparedStatement ps2 = conn.prepareStatement(sql2);
rscirculation = ps2.executeQuery() ;
if(rscirculation!=null){
while(rscirculation.next())
{
JSONObject jobj = new JSONObject();
display = rscirculation.getString("DisplayName");
des=rscirculation.getString("Description");
jobj.put("DisplayName", display);
jobj.put("Description", des);
jArraycirculation.add(jobj);
}
usesfactors.put("Circulation", jArraycirculation);
rscirculation.close();
}
else{
System.out.println("Does not have Circulation factors");
}
out.println(usesfactors);
}
i am getting empty json result....?Whts wrong?
{"Size":[],"Circulation":[]}
i don't want to execute this stmt "usesfactors.put("Size", jArraysize);" if resultset rssize is null but this stmt is executing even if result set rssize has no records....
In short i want to put json array(jArraysize) in json object (usesfactors) if and only if result set rssize has records.
In response to the question in the code about why it's getting into the rssize!=null block, see the javadoc on executeQuery. It explicitly states that it never returns null, so the null check always passes. This means that an empty result set will skip the loop in that section, but still hit the line
usesfactors.put("Size", jArraysize);
This should be rewritten to actually avoid the insert on an empty return set. A similar change should be made to correct the circulation section, which also does an ineffective null check.
while(rssize.next())
{
System.out.println("inside resultset");
JSONObject jobj = new JSONObject();
sizeid = rssize.getInt("SizeId");
size=rssize.getString("Size");
System.out.println(size);
jobj.put("SizeId", sizeid);
jobj.put("Size", size);
jArraysize.add(jobj);
}
if (jArraysize.length > 0)
{
usesfactors.put("Size", jArraysize);
}
else
{
System.out.println("Does not have Size factors");
}
rssize.close();
The problem in your code might be your sql queries which are not returning any values.because i have done in my IDE in the same way you have done,only difference is that instead of getting values from database i have kept manually by iterating for loop.below is the code...
JSONObject usesfactors = new JSONObject();
JSONArray jArraysize = new JSONArray();
JSONArray jArraycirculation = new JSONArray();
for(int i=0;i<3;i++)
{
JSONObject jobj = new JSONObject();
jobj.put("SizeId", "1");
jobj.put("Size", "2");
jArraysize.put(jobj);
}
usesfactors.put("Size", jArraysize);
for(int i=0;i<3;i++)
{
JSONObject jobj = new JSONObject();
jobj.put("DisplayName", "3");
jobj.put("Description", "4");
jArraycirculation.put(jobj);
}
usesfactors.put("Circulation", jArraycirculation);
System.out.println(usesfactors);

Load database Field Values to A JCombobox

How to load values from an Oracle db to a JComboBox to make it easier for the user To Choose from I Have tried this:
Connection dbcon = null;
try {
Class.forName("oracle.jdbc.driver.OracleDriver");
dbcon = DriverManager.getConnection("
jdbc:oracle:thin:#localhost:1521:XE", "USERNAME", "PASSWORD");
Statement st = dbcon.createStatement();
String combo = "Select EMP_IDNUM from employees";
ResultSet res = st.executeQuery(combo);
while(res.next()){
String ids = res.getString("EMP_IDNUM");
String [] str = new String[]{ids};
cboId = new JComboBox(str);
}
} catch (Exception d) {
System.out.println(d);
}
This is Only getting me the first Value Into the JComboBox cboID. What Is the Best way to Load the entire Field Data (EMP_IDNUM) into the Jcombobox??
String [] str = new String[]{ids};
It means your String array is having only one ids value which you have loaded String ids = res.getString("EMP_IDNUM");
if(rs.getRow()>0){
String [] str = new String[res.getRow()];
int i=0;
while(res.next()){
str[i++] = res.getString("EMP_IDNUM");
}
}
JComboBox jcb = new JComboBox(str);
Instead of array you can use Vector also to create JComboBox.
you can use this code:
Vector v = new Vector();
while(res.next()){
String ids = res.getString("EMP_IDNUM");
v.add(ids)
}
JComboBox jcb = new JComboBox(v);
In this code you create a Vector with your Strings, and then invoke directly the JComboBox(Vector items) constructor of JComboBox
there are three important areas
a) close all JDBC Objects in the finally block, because these Object aren't, never GC'ed
try {
} catch (Exception d) {
System.out.println(d);
} finally {
try {
st.close()
res.close()
dbcon.close()
} catch (Exception d) {
//not important
}
}
b) don't to create any Objects inside try - catch - finally, prepare that before
meaning cboId = new JComboBox(str);
c) put all data from JDBC to the ComboBoxModel, prepare that before

Categories