Convert jsonarray to string - java

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");

Related

Can't get all dataColumn values by ResultSet

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;
}

I want to get list of top 250 movies of imdb but I'm unable as it give me "{}" not whole list

I have added libraries properly there is no one error but it is not showing desired result. I have got the return type string and saved it to a variable and then set it text view. I have stuck here. Please help me.
public String TableToJson() throws JSONException {
int i=0;
String s="http://www.imdb.com/chart/top";
Document doc = Jsoup.parse(s);
JSONObject jsonParentObject = new JSONObject();
//JSONArray list = new JSONArray();
for (Element table : doc.select("table")) {
for (Element row : table.select("tr")) {
JSONObject jsonObject = new JSONObject();
Elements tds = row.select("td");
i++;
String no = Integer.toString(i);
String Name = tds.get(1).text();
String rating = tds.get(2).text();
jsonObject.put("Ranking", no);
jsonObject.put("Title", Name);
jsonObject.put("Rating", rating);
jsonParentObject.put(Name, jsonObject);
}
}
return jsonParentObject.toString();
}
and output is only
{}
As you can see just using a regular expression will work for you.
Sample query can be similar to this
<strong title=".*</strong>
Showing 250 matches Tested using freeformatter

JSON Parsing in Java Webservice of multiple JSONObjects in JSONObject

This is my JSON string,
{
"listmain":{
"16":[{"brandid":"186"},{"brandid":"146"},{"brandid":"15"}],
"17":[{"brandid":"1"}],
"18":[{"brandid":"12"},{"brandid":"186"}],
}
}
I need to get values in "16","17","18" tag and add values and ids("16","17","18") to two ArrayList.
What i meant is,
when we take "16", the following process should happen,
List<String> lsubid = new ArrayList<String>();
List<String> lbrandid = new ArrayList<String>();
for(int i=0;i<number of elements in "16";i++) {
lsubid.add("16");
lbrandid.add("ith value in tag "16" ");
}
finally the values in lsubid will be---> [16,16,16]
the values in lbrandid will be---> [186,146,15]
Can anyone please help me to complete this.
Use JSONObject keys() to get the key and then iterate each key to get to the dynamic value.
You can parse the JSON like this
JSONObject responseDataObj = new JSONObject(responseData);
JSONObject listMainObj = responseDataObj.getJSONObject("listmain");
Iterator keys = listMainObj.keys();
while(keys.hasNext()) {
// loop to get the dynamic key
String currentDynamicKey = (String)keys.next();
//store key in an arraylist which is 16,17,...
// get the value of the dynamic key
JSONArray currentDynamicValue = listMainObj.getJSONArray(currentDynamicKey);
int jsonrraySize = currentDynamicValue.length();
if(jsonrraySize > 0) {
for (int i = 0; i < jsonrraySize; i++) {
JSONObject brandidObj = currentDynamicValue.getJSONObject(i);
String brandid = brandidObj.getString("brandid");
System.out.print("Brandid = " + brandid);
//store brandid in an arraylist
}
}
}
Source of this answer

Error when using JSONSimple to write a json file with for loop

I need to transform my data in a ArrayList to a JSON file, and I use JSON.simple. Everything is fine except one little thing that I want to get a result like ...... {source:0, target:1},{source:0, target:1},{source:0, target:2},{source:0, target:3} ...... but it returns ......{source:0, target:16},{source:0, target:16},{source:0, target:16}...... . My solution.size() is 17.
Here is my code:
JSONObject jsonObject = new JSONObject();
JSONObject jsonNodesObject = new JSONObject();
JSONObject jsonEdgesObject = new JSONObject();
JSONArray jsonNodesArray = new JSONArray();
JSONArray jsonEdgesArray = new JSONArray();
String instString = solutions.get(0).get("institution");
jsonNodesObject.put("name", instString);
// extract name and institution from ArrayList
for (int i = 0; i < solutions.size(); i++)
{
HashMap<String, String> eleHashMap= solutions.get(i);
String nameString = eleHashMap.get("name");
jsonNodesObject.put("name", nameString);
jsonNodesArray.add(jsonNodesObject);
jsonEdgesObject.put("source", 0);
jsonEdgesObject.put("target", i);
jsonEdgesArray.add(jsonEdgesObject);
}
jsonObject.put("nodes", jsonNodesArray);
jsonObject.put("edges", jsonEdgesArray);
System.out.println(jsonObject);
It seems that in every for loop, it refreshes the value of target: i of all my jsonEdgesArray.
Dose anyone know how to fix this? Thanks in advance!
As your iterating jsonNodesObject in for loop, same value will be put for jsonNodesObject.put("name", nameString); u have to initialize JSONObject jsonNodesObject = new JSONObject(); inside for loop

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);

Categories