I have table named testTable( in sql server 2014) and i have one column called holidays inside it , in my case i have two values inside this column for example (2018-03-02 and 2018-04-02) and i use this method for getting this value and then puttinh it in json Object here is my code:
public static JSONArray convertToJSON(ResultSet resultSet) throws Exception {
JSONArray jsonArray = new JSONArray();
JSONObject obj = new JSONObject();
while (resultSet.next()) {
int total_rows = resultSet.getMetaData().getColumnCount();
for (int i = 0; i < total_rows; i++) {
jsonArray.put(obj.put(resultSet.getMetaData().getColumnLabel(i+1)
.toLowerCase(), resultSet.getObject(i+1)));
}
}
System.out.println(jsonArray);
return jsonArray;
}
but when i run this code i got only last data written two times in my array it will look like this :
[{"startDate":2018-03-02},{"startDate":2018-03-02}]
but it should look like this:
[{"startDate":2018-03-02},{"startDate":2018-03-03}]
I mean it writes last data twice but when i try to print it in console i got right values?
what should i change to get all startDate values properly?
You are overwriting the record by doing the following operation
jsonArray.put(obj.put(resultSet.getMetaData().getColumnLabel(i+1)
.toLowerCase(), resultSet.getObject(i+1)));
While putting the object your key is startdate which gets overwritten
obj.put(resultSet.getMetaData().getColumnLabel(i+1)
.toLowerCase(), resultSet.getObject(i+1))
Also, there is something wrong with your logic. The following code will give you column count and NOT the row count
int total_rows = resultSet.getMetaData().getColumnCount();
You can use the following snippet to get the object:
public static JSONArray convertToJSON(ResultSet resultSet) throws Exception {
JSONArray jsonArray = new JSONArray();
while (resultSet.next()) {
JSONObject obj = new JSONObject();
obj.put("startDate" , resultSet.getString('holidays'))
jsonArray.put(obj);
}
return jsonArray;
}
Related
I want to get all the data from the database using a where condition. But resultSet returning null values. But when I use an Integer instead of string it works fine, but that I don't want.
I'm not many experts in SQL but when I run a query in SQL server it works fine.
public JSONObject searchInternship1(String Category) throws SQLException {
ResultSet result;
Connection con = null;
PreparedStatement stmt = null;
JSONArray jsonArray = new JSONArray();
JSONObject mainObject1 = new JSONObject();
JSONObject jsonObject = new JSONObject();
try {
DriverManager.registerDriver(new oracle.jdbc.OracleDriver());
con = DriverManager.getConnection("jdbc:oracle:thin:#144.217.163.57:1521:XE", "mad310team2", "anypw");
String sql;
sql = ("SELECT * FROM INTERNSHIP WHERE CATEGORY= ?");
stmt = con.prepareStatement(sql);
// con.setTransactionIsolation(Connection.TRANSACTION_READ_COMMITTED);
stmt.setString(1, Category);
result = stmt.executeQuery();
System.out.println("resultttt " + result);
String status;
Instant instant = Instant.now();
long time = instant.getEpochSecond();
if (result.next() == false) {
status = "Failed";
mainObject1.accumulate("Status :", status);
mainObject1.accumulate("Timestamp :", time);
mainObject1.accumulate("Message :", " Fetching Failed");
mainObject1.accumulate("why not", Category);
// System.out.println("hellooooo "+ result);
} else {
do {
mainObject1.accumulate("why not111", Category);
status = "Success";
jsonObject.accumulate("Id :", result.getInt("INT_ID"));
jsonObject.accumulate("CONTACT PERSON", result.getString("CONTACT_PERSON"));
jsonObject.accumulate("INCENTIVE", result.getString("INCENTIVE"));
jsonObject.accumulate(" VENUE", result.getString("VENUE"));
jsonObject.accumulate("DATE OF TEST", result.getDate("DATE_OF_TEST").toString());
jsonObject.accumulate("DATE OF TEST", result.getString("TIME_OF_TEST"));
jsonObject.accumulate("PROCEDURE", result.getString("PROCEDUREE"));
jsonObject.accumulate("No. OF VACANCIES", result.getInt("NO_OF_VACANCIES"));
jsonObject.accumulate("COMPANY ID", result.getInt("COMPANY_ID"));
jsonObject.accumulate("CATEGORY", result.getString("CATEGORY"));
jsonArray.add(jsonObject);
jsonObject.clear();
} while (result.next());
// result = result + r.getString("data");
mainObject1.accumulate("Details of jobs: ", jsonArray);
}
stmt.close();
con.close();
} catch (SQLException ex) {
// System.out.println("Error at111:" + ex.getClass().getName() + ex.getMessage());
Logger.getLogger(Register_Detail.class.getName()).log(Level.SEVERE, null, ex);
}
return mainObject1;
}
#GET
#Path("searchInternship&{value1}")
#Produces(MediaType.TEXT_PLAIN)
public String searchInternship(#PathParam("value1") String Category)
throws SQLException {
JSONObject result = searchInternship1(Category);
return result.toString();
}
I don't believe this is a JDBC issue. I believe this is an issue with how you are reading the data out of the result set.
At the top of your createInternship1 method you create a JSONObject object. Let's suppose at least one row comes back from the result set. For the first row read from the result set, your code then reads the values out of the result set and writes them into your JSONObject, before adding your JSONObject to your JSON array jsonArray.
So far, your code is doing what you want it to. You have a JSON array with a single object in it, containing the data read from the first row in the result set. However, the problem comes with your next step.
You then clear your JSONObject.
Your array doesn't contain a copy of your JSONObject, it contains the same object.
So at this point, your array now contains a single empty JSONObject. The data you read out of the result set has been deleted.
As your code proceeds through further rows in the result set, it encounters another problem. It reads more data into the same JSONObject created earlier, adds this same JSONObject (which is already in the array) to the array and then clears this same JSONObject again. You therefore end up with a JSON array containing the same empty JSONObject once for each row read from the result set.
I figured you're using the json-simple library for handling JSON. Initially I thought you were using org.json, but the JSONObject class in that library doesn't have a clear() method, whereas json-simple's JSONObject class does have this method. json-simple's JSONObject class extends java.util.HashMap, and calling the get() method of a HashMap returns null for a key that is not in the map. Your one JSONObject is empty, so no keys are in the map, and so null will always be returned from any call to the get() method of this object. This hopefully explains why you are getting null values returned.
You can fix this by creating a new JSONObject for each iteration of your do ... while loop instead of once at the top, adding that to your JSON array, and removing the line that clears the JSON object:
do {
JSONObject jsonObject = new JSONObject(); // add this line
mainObject1.accumulate("why not111", Category);
status = "Success";
jsonObject.accumulate("Id :", result.getInt("INT_ID"));
jsonObject.accumulate("CONTACT PERSON", result.getString("CONTACT_PERSON"));
// ... various similar lines omitted for clarity
jsonObject.accumulate("CATEGORY", result.getString("CATEGORY"));
jsonArray.add(jsonObject);
} while (result.next());
You'll also need to delete the line JSONObject jsonObject = new JSONObject(); further up in your code.
I am trying to parse a REST API that has 3 possible variations. The first one is the one I already have working where there is an array for the "row" output as shown in the photo below.
There is also row as an object, as pictured below.
And finally, one where there is no data, as shown below.
Any one of these is a possible output when parsing the API, I need something like an if statement to see which one is the output and parse the information from there, but I do not know how to create an if statement for this particular need. Here is my current code:
JSONObject parentObject = new JSONObject(finalJson);
JSONObject responseJSON = JSONUtils.jsonObjectFromJSONForKey(parentObject, "response");
if (responseJSON != null) {
JSONObject resultJSON = JSONUtils.jsonObjectFromJSONForKey(responseJSON, "result");
JSONObject contactsJSON = JSONUtils.jsonObjectFromJSONForKey(resultJSON, "Potentials");
JSONArray parentArray = contactsJSON.getJSONArray("row");
List<Photoshoots> photoshootsList = new ArrayList<>();
for (int i = 0; i < parentArray.length(); i++) {
JSONObject mainObject = parentArray.getJSONObject(i);
JSONArray mainArray = mainObject.getJSONArray("FL");
Photoshoots photoshoot = new Photoshoots();
...
I have solved the problem I was having. It may not be the ideal way to solve the problem, but it does work. Inside of the doInBackground in AsyncTask, I had initially converted the JSON result data into a StringBuffer, then converted the StringBuffer to a String. I then used one if and 2 else if statements to parse the data. The first if statement checks if the JSON string contains the phrase "nodata" representing that no data matches my original criteria, shown below:
if (finalJson.contains("nodata"))
I then had it pass on null data to be checked in onPostExecute for later. Next else if statement checked to see if row is an array. The way I did that was check to see if the string had a [ after row, indicating that it was an array, shown below:
else if (finalJson.contains("{\"response\":{\"result\":{\"Potentials\":{\"row\":["))
I then parsed the information as follows:
JSONArray parentArray = contactsJSON.getJSONArray("row");
for (int i = 0; i < parentArray.length(); i++) {
JSONObject mainObject = parentArray.getJSONObject(i);
JSONArray mainArray = mainObject.getJSONArray("FL");
the final else if, which could probably just be an else statement, is almost the same, except looking for a { after row instead of [, indicating it was just an object, as shown below:
else if (finalJson.contains("{\"response\":{\"result\":{\"Potentials\":{\"row\":{"))
I then parsed the information as follows:
JSONObject mainObject = contactsJSON.getJSONObject("row");
JSONArray mainArray = mainObject.getJSONArray("FL");
Inside of the onPostExecute, I have a code that will run a class that extends ArrayAdapter for the results contained in both of the else if statements, but I don't want it to run if there is no data, so I did the following:
protected void onPostExecute(List<Photoshoots> result) {
super.onPostExecute(result);
if (result != null) {
PhotoshootAdapter adapter = new PhotoshootAdapter(getApplicationContext(), R.layout.row, result);
lvPhotoshoots.setAdapter(adapter);}
else{
new CountDownTimer(60000, 1000) {
public void onTick(long millisUntilFinished) {
btnRefresh.setText("No Data to Show. Try again in " + millisUntilFinished / 1000 + " Seconds");
}
public void onFinish() {
btnRefresh.setText("Refresh");
btnRefresh.setEnabled(true);
}
}.start();
The result will pass the null data if there is nodata, but a list if there is data within the result. Like I said, there may be a better way to solve this problem, but the app works now and it doesn't crash regardless of the data that is returned.
I want to put value of first query (course) to other query (mapcategory) in my code.
The value in first query not convert to string in second query.
public String query() throws Exception {
JSONObject inputJsonObj = new JSONObject();
JSONArray inputArray = new JSONArray();
String array=null;
Database db = new Database();
db.my_Connection();
List<HashMap> course = db.Query("select NAME from file where visual_code='1'");
inputArray = new JSONArray();
if(course !=null)
for (int i=0; i<course.size(); i++){
HashMap data=(HashMap)course.get(i);
inputJsonObj = new JSONObject();
inputJsonObj.put("NAME",(String) data.get("NAME"));
inputArray.put(inputJsonObj);
}
arra=String.valueOf(course);
List<HashMap> mapCategory = db.Query("select PATH from c_"+arra+"_item item" +
" LEFT JOIN cr_"+arra+"_document doc" +
" ON item.ref = doc.id WHERE visibility = 1 AND tool = 'document'");
inputArray = new JSONArray();
if(mapCategory !=null)
for (int i=0; i<mapCategory.size(); i++){
HashMap data=(HashMap)mapCategory.get(i);
inputJsonObj = new JSONObject();
inputJsonObj.put("PATH",(String) data.get("PATH"));
inputArray.put(inputJsonObj);
}
db.Close_Connection();
return inputArray.toString();
}
i debuging this code and get an eror
HTTP Status 500 -
com.sun.jersey.api.container.MappableContainerException:
com.mysql.jdbc.exceptions.MySQLSyntaxErrorException: You have an error
in your SQL syntax; check the manual that corresponds to your MySQL
server version for the right syntax to use near
'{NAME=TUTORIAL}_item_property item LEFT JOIN
crs_{NAME=TUTORIAL}_d' at line 1
I want get value only "TUTORIAL" in result.
your problem is in arra=String.valueOf(course); cuz you are save string representation of hashmap in string instead you need a value from hashmap.
replace
arra=String.valueOf(course);
to
arra=course.get("NAME");
I have a JSON Object which converted into String and saved into database .But when i am trying to get it back it is throwing exception.My object is something like that...
{"COLUMN":["Type","Sub Type","F.P.","P.P.","Process","Due To Start"]}
How can we get the data back in Normal form?
My Java Code is.....
JSONObject obj = new JSONObject();
JSONArray the_json_array = obj.getJSONArray(userReorderOption);
int size = the_json_array.size();
ArrayList<JSONObject> arrays = new ArrayList<JSONObject>();
for (int i = 0; i < size; i++) {
JSONObject another_json_object = the_json_array.getJSONObject(i);
arrays.add(another_json_object);
}
And Exception i am getting....
net.sf.json.JSONException: JSONObject["{\"TASKLIST_COLUMN_REORDER\":[\"Type\",\"Sub Type\",\"F.P.\",\"P.P.\",\"Process\",\"Due To Start\"]}"] is not a JSONArray.
And this is java Code how i am creating JSON Object and saving into database...
String userReorderSelection;
Set set = new LinkedHashSet(userReorderSelection);
JSONObject json = new JSONObject();
json.accumulate("COLUMN", set);
saveJSONObj("PrimaryKeyColumn", json.toString());
Thanks Tichodroma,
But as i told i am using net.sf.json.JSONObject class and above things we can achieve from this class too..What i did to solve the above issue?...Please have a look on the Java code...
JSONObject jsonObj = new JSONObject();
JSONObject obj = jsonObj.fromObject(userReorderOption);
JSONArray columnName = (JSONArray) obj.get("COLUMN");
for (int i = 0; i < columnName.size(); i++) {
System.out.println(columnName.getString(i));
}
This code work fine for me with my Json Jar**(net.sf.json)**
Your JSON is not a JSONArray.
A JSONArray is an ordered sequence of values.
You have a JSONObject.
A JSONObject is an unordered collection of name/value pairs.
Edit:
Using the JSON implementation from org.codehaus.jettison.json, you can do this:
String json = "{\"COLUMN\":[\"Type\",\"Sub Type\",\"F.P.\",\"P.P.\",\"Process\",\"Due To Start\"]}";
JSONObject obj = new JSONObject(json);
JSONArray column = (JSONArray) obj.get("COLUMN");
for (int i = 0; i < column.length(); i++) {
final String field = column.getString(i);
System.out.println(field);
}
Result:
Type
Sub Type
F.P.
P.P.
Process
Due To Start
I have written java code for generating json of my searched data from file.But its not generating exact JsonArray. Its like
[{"item":"1617"},{"item":"1617"}]
instead of
[{"item":"747"},{"item":"1617"}].
Here 1617 is last item which is fetched from file.
JSONArray ja = new JSONArray();
JSONObject jo = new JSONObject();
while (products.readRecord())
{
String productID = products.get("user");
int j = Integer.parseInt(productID);
if(j == userId) {
itemid = products.get("item");
jo.put("item",itemid);
ja.add(jo);
}
}
out.println(ja);
products.close();
you are actually creating one jSONobject object to handle two objects, shouldn't you need to create JSONObjects in the while loop? something like this, so every iteration in while loop will create a new JSONObject and add it to JSONArray
JSONArray ja = new JSONArray();
while (products.readRecord())
{
String productID = products.get("user");
int j = Integer.parseInt(productID, 10);
if(j == userId)
{
JSONObject jo = new JSONObject();
itemid = products.get("item");
jo.put("item", itemid);
ja.add(jo);
}
}
out.println(ja);
products.close();
Extra:
i am not sure how java does conversion for string to integer, but i think you should always specify radix when using parseInt so the strings like '09' will not be treated as octal value and converted to wrong value (atleast this is true in javascript :))
Integer.parseInt(productID, 10);
You must re-instantiate your JSonObject inside the loop because when you modify it you modify the underlying object which is referenced several times by your array. Move your JSONObject jo = new JSONObject(); inside the loop and it should work fine.
Place JSONObject jo = new JSONObject(); inside the loop:
while (products.readRecord())
{
JSONObject jo = new JSONObject();
String productID = products.get("user");
int j = Integer.parseInt(productID);
// etc
}