I'm from the PHP background, so pardon my noobness. I'm required to use JSON in one of my projects and I cannot, for the life of me, determine how to import and use the GSON library.
I followed Adding library to Eclipse and Using GSON threads but for some reason my code isn't working.
The aim is to pass an ArrayList object back as a JSON array so that I can use Jquery (inside Ajax success function) to iterate over it.
But when I use the following (This is not a class, simply a jsp file which connects to database, pulls some info, and stores it in an ArrayList):
<%# page import="java.sql.*"%>
<%# page import="java.util.*"%>
<%
String kw = request.getParameter("key");
try {
java.sql.Connection con;
Class.forName("com.mysql.jdbc.Driver");
con = DriverManager.getConnection("jdbc:mysql://localhost:3306/abcd", "root", "pass");
st = con.createStatement();
rs = st.executeQuery("SELECT DISTINCT t.tckid FROM ticket t WHERE t.tckid LIKE '%"+kw+"%'");
ArrayList<String> tickets = new ArrayList<String>();
while(rs.next()) {
String TCKTID = rs.getString(1);
tickets.add(TCKTID);
}
rs.close();
st.close();
con.close();
Gson gson = new Gson(); // this is giving me Gson cannot be resolved to a type
So of what I can gather, the Gson class didn't get imported at all. Is there a way to verify the successful import of the library? Or do I also need to use some import *** code on the top of the file?
The problem is that you are not importing the Gson package in your current JSP.
<%
Gson gson=new Gson();
%>
importing in JSP
<%# page import="com.google.gson.Gson" %>
but please keep in mind to avoid using scriptlets in your JSPMVC pattern to separate the server side with the client side actions/purpose. if you want to display values coming from the database you could always use JSTL and using different scopes(request scope,session scope, etc).
Related
I am creating a web aplication using Angular 8 for the frontend, and Spring Boot for the backend (I am quite new to SpringBoot programming)
I have a table with a list of "protocols" and a checkbox filter above it. Here is a screenshot of the webpage:
When I click "Apply Filters" button, it generates a JSON array like this:
[{subject_id:[2,3]},{scenario_id:[2]},{algorithms_id:[2]}]
Now, in the backend, I want to create a filter using this JSON array, so that it returns only the corresponding protocols. I guess I have to use a Query functionality and #GetMapping in java SpringBoot. But I don't know how to specify which JSON item to use for each attribute of "protocol". If you could give me some advice on how to do this, I would really appreciate it.
Why not make a Java class - Filter.java with fields :
private List<String> subject_id=new ArrayList<>();
private List<String> scenario_id=new ArrayList<>();
private List<String> algorithms_id=new ArrayList<>();
and then write a POST controller with a RequestBody like:
#RequestMapping(value = "/myapi", method = RequestMethod.POST)
public ResponseEntity<String> getResultsByFilter(
#RequestBody(required = true) List<Filter> filters)
this way you can get the filter in the request body and then process it as per your business logic to return results as you want them.
I'm trying to make a dynamic jsp page based on the json.
For example, if my json is look like this:
{
'page1':'true',
'page2':'true',
'page3':'false'
}
In php, I could get my associative array easily by one line:
$data = json_decode($json_str);
Then I could access whichever that I wanted at the place I needed, (i.e)
If($data['page1'] == 'true')
echo #page link#;
But in jsp, it doesn't goes so easily because it don't have much documents like php. I find the gson but still not sure. how to use it to achieve it.
Please give me some example that I could turn json to associative array, then get and access it in jsp.
A Java Map is an associative array. You can ask Gson to deserialize your json input with this:
Map<String,String> map = new Gson().fromJson(inputJson, new TypeToken<Map<String,String>>() {}.getType());
Example code:
package net.sargue.gson;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import java.lang.reflect.Type;
import java.util.Map;
public class SO36859440 {
public static void main(String[] args) {
String inputJson = "{\n" +
" 'page1':'true',\n" +
" 'page2':'true',\n" +
" 'page3':'false'\n" +
"}";
Type type = new TypeToken<Map<String, String>>() {}.getType();
Map<String,String> map = new Gson().fromJson(inputJson, type);
System.out.println(map.get("page2"));
System.out.println(map.get("page3"));
}
}
The output is:
true
false
Then, your question is about converting it in JSP. Well, best practices for JSP advice you to move this kind of processing to a Servlet that acts as a controller and passes attributes to the JSP in order to build the view. You can put code directly on the JSP using <% ... %> but I highly discourage you to do so. But that's an entirely different question.
I am working on an Android app, for which I am also working on a
Spring-MVC based server. Unfortunately before this, I have not done
that much work on JSONObjects. Currently, I am able to send Java
objects to the server from the Android app, and receive Java objects
too.
I am interested in using the Volley framework provided by Google,
which will avoid the hassle of Asynctask and is more efficient, but
it deals with JSONObject.
Unfortunately wherever I looked on the net, I found the code to
create JSOnObjects to save it in some file on Local Hard drive, but
no, I would like to transmit them in ResponseBody, can anyone help me
out with creating a JAVA object to JSOBObject and vice-versa. I have
all POM dependencies, and messageConvertors set in servlet-context.
Controller code current :
//Restaurant is just a plain Java class, I can give it as a JSONObject, but I dont know how to convert that JSONObject to java so I can save the restaurant in the server.
#RequestMapping(value = "/restaurant/add",method = RequestMethod.POST)
#ResponseBody
public String addRestaurantWebView(#RequestBody Restaurant restaurant){
ModelAndView modelAndView = new ModelAndView();
modelAndView.addObject("restaurant", new Restaurant());
modelAndView.addObject(restaurant);
this.restaurantService.addRestaurant(restaurant);
return "true";
}
//Similarly, here, I don't know how to convert the Restaurant's list to JSONObject when there is a get Request.
#RequestMapping(value = "/restaurant/listing", method = RequestMethod.GET)
public #ResponseBody List<Restaurant> listAllRestaurants(){
ModelAndView modelAndView = new ModelAndView();
modelAndView.addObject("restaurant", new Restaurant());
List<Restaurant> restaurantList = this.restaurantService.listRestaurants();
modelAndView.addObject("listRestaurant", restaurantList);
return restaurantList;
}
I hope my question was clear, if there is any doubt, please let me know. Thanks a lot.
Take a look at Google's Gson. It's a pretty concise API for converting objects to JSON. You can easily specify properties by adding the #Expose annotation in your classes to the properties you need to include. Try it like this:
#RequestMapping(value = "/restaurant/listing", method = RequestMethod.GET)
public #ResponseBody String listAllRestaurants(){
ModelAndView modelAndView = new ModelAndView();
modelAndView.addObject("restaurant", new Restaurant());
List<Restaurant> restaurantList = this.restaurantService.listRestaurants();
Gson gson = new GsonBuilder().excludeFieldsWithoutExposeAnnotation().create();
String jsonString = gson.toJson(restaurantList);
return jsonString;
}
It's not necessary to annotate properties with #Expose but it will help if you end up having any circular references.
Good luck.
How to configure JSON jar files in jsp?
I am getting error in JSONObject class.
In Java:
// Assuming 'request' is HttpServletRequest
String jsonString = request.getParameter("jsonData");
JSONObject jsonObject = (JSONObject) JSONValue.parse(jsonString);
JSONObject jo=new JSONObject(jsonString);
will do the trick.
#user2866902 Do you have jar file in your classpath? Here i used json_simple-1.1.jar for my purpose. You need to import the jar file in jsp, like
<%#page import="org.json.simple.JSONObject"%>
Then you can get the json object like this,
<% net.sf.json.JSONObject responcedata = new net.sf.json.JSONObject(); %>
Hope this helps you..
My JSP, is being passed an JSONObject in the context, on which it needs to do some processing like creating tables, etc.
But when I try to access the member of this object, it gives the following error -
(the name of one of the keys in this object is ok)
Servlet.service() for servlet jsp threw exception { javax.servlet.jsp.el.ELException:
Unable to find a value for "ok" in object of class "org.json.JSONObject" using operator "."
JSP Code accessing it looks like this -
<%# taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<c:if test="${serviceOutput.ok}">
<c:if test="${serviceOutput.ret.proposalCount} > 0">
.....
Can anyone please suggest how I can resolve this and successfully access all the members of this object?
The other option that could be taken now is to use a different JSON parsing library such as json-simple (http://code.google.com/p/json-simple/). The JSONObject in this library extends HashMap and the JSONArray extends an ArrayList, so EL should work with them. You would then not have to change your jstl or do extra parsing.
EL only understands Javabeans and Maps. You need to let a preprocessing servlet convert each item of the JSONObject to a fullworthy Javabean which has getter methods which can be used in EL, or to a Map.
Here's an example which converts it to a Map:
Map<String, Object> serviceMap = new HashMap<String, Object>();
serviceMap.put("ok", serviceOutput.getBoolean("ok"));
serviceMap.put("foo", serviceOutput.getString("foo"));
// ...
request.setAttribute("serviceMap", serviceMap);
request.getRequestDispatcher("/WEB-INF/page.jsp").forward(request, response);
This way EL expressions like ${serviceMap.ok} will work.