How to configure JSON jar files in jsp - json

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..

Related

Nested JSON with root element not having key and it is varying

I have a unique requirement where i need to construct a JSON as below.
{
"XXXMonitoring/DC/EVN/DBNAME":{
"t":123456777,
"s":{
"CAPTURE":{
"c":100
}
}
}
}
where the root element "XXXMonitoring/DC/EVN/DBNAME" contains "/" in between as it represents a path. I tried with GSON to have nested java but not sure how i can represent "XXXMonitoring/DC/EVN/DBNAME" from my Java object.
Can someone help me on this.
I'm not sure if this is what are you asking...
But sollidus (/) is escaped by backslash (\) to be sure that the browser won’t mistake it for the closing script tag
when you need to use that key, you can remove backslash with String.replaceAll() method
json.toString().replaceAll("\\\\", "");
The JSON string can be constructed without POJO class using the below code.
If the JSON structure is same and only values will change for the keys, you can replace the hard coded values with variables and convert this into an utility method. The utility method can be reused to generate the JSON string.
public static void main(String[] args) throws IOException {
Gson gson = new Gson();
JsonObject jsonRootObject = new JsonObject();
JsonObject jsonFirstLevelObject = new JsonObject();
// t property
jsonFirstLevelObject.addProperty("t", 123456777);
JsonObject jsonCaptureObject = new JsonObject();
JsonObject jsonCObject = new JsonObject();
jsonCObject.addProperty("c", 100);
jsonCaptureObject.add("CAPTURE", jsonCObject);
// s property
jsonFirstLevelObject.add("s", jsonCaptureObject);
jsonRootObject.add("XXXMonitoring/DC/EVN/DBNAME", jsonFirstLevelObject);
System.out.println(gson.toJson(jsonRootObject));
}
I have a library called GsonPath which might suit your needs. The aim of the library is to provide an annotation processor that generates the boilerplate code to help simplify the POJO you need to write.
By using the library you can write a POJO similar to the following:
#AutoGsonAdapter(rootField = "XXXMonitoring/DC/EVN/DBNAME")
public class SamplePojo {
int t;
#SerializedName("s.CAPTURE.c")
int sCapture;
}
Then all you need to do in your gson object is to register a special TypeAdapterFactory
GsonBuilder builder = new GsonBuilder();
builder.registerTypeAdapterFactory(GsonPath.createTypeAdapterFactory());
Gson gson = builder.create();
The documentation within the library is faily comprehensive, let me know if you have any problems!

RestFul cucumber acceptance test to get local file json as output

I want to mock a resttemplate output. We have a service /someservice/getJson to get json. To mock this service we kept a json file in the code base and tried to get it to the response entity as follows.
working code:
String baseURL = "http://localhost:1010"
String uri = /someservice/getJson
ResponseEntity<T> entity = restTemplate.exchange(baseURL + uri, GET, new HttpEntity<>(headers), type);
I have a json file in the code base (say codebase/../resource/myfile.json)
I would like to get the response entity as the local json I mock.
I tried using exchange method. It doesnt seems as working for me.
What I tried with my json file
String localJson = "/resource/myfile.json";
ResponseEntity<T> entity = restTemplate.exchange(localJson, GET, new HttpEntity<>(headers), type);
I think there are another methods to get it done other than exchange. But I am not aware of those.
Is there any other way / is there any mistake in what I tried ?
To read a file with JSON object and convert it into a POJO you can use ObjectMapper’s
readValue(File src, Class<T> valueType) method (readValue doc link) from Jackson framework:
import java.io.File;
import com.fasterxml.jackson.databind.ObjectMapper;
ObjectMapper mapper = new ObjectMapper();
YourJsonType response = mapper.readValue( new File("file with JSON object") , YourJsonType.class);

How to Include and Use GSON library in Eclipse project

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

Create JSON/GSON from json file within a jar

I use Google's GSON library to generate GSON/JSON objects.
However, now I have the problem that I need to create a GSON object for a file within a jar.
I can get a InputStream, BufferedReader or Properties from the json file I want to parse to an GSON object, however the Gson().toJson() then Gson().fromJson can't generate a GSON object from any of the above mentioned.
So, how would I access a json file within a jar and pass it to the GSON library to get a GSON file?
Right now I have something along this line:
public class Main {
public static void main(String[] args) throws IOException {
JarFile jar;
jar = new JarFile("path.jar");
InputStream inputStream = jar.getInputStream(jar.getEntry("file.json"));
}

Accessing JSONObject in jsp

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.