I have a JSON object sent from the browser to the jsp page.How do I receive that object and process it in jsp.Do I need any specific parsers? I have used the following piece of code.But it wouldn't work.Essentially I should read the contents of the object and print them in the jsp.
<%#page language="java" import="jso.JSONObject"%>
<%
JSONObject inp=request.getParameter("param1");
%>
<% for(int i=0;i<inp.size();i++)
{%>
<%=inp.getString(i)%>
<%
}
%>
My preferred solution to this problem involves using a JSON parser that provides an output that implements the java.util.Map and java.util.List interface. This allows for simple parsing of the JSON structure in the JSP Expression language.
Here is an example using JSON4J provided with Apache Wink. The sample imports JSON data from a URL, parses it in a java scriptlet and browses the resulting structure.
<c:import var="dataJson" url="http://localhost/request.json"/>
<%
String json = (String)pageContext.getAttribute("dataJson");
pageContext.setAttribute("parsedJSON", org.apache.commons.json.JSON.parse(json));
%>
Fetch the name of the node at index 1 : ${parsedJSON.node[1].name}
To make this clean, it would be preferable to create a JSTL tag to do the parsing and avoid java scriplet.
<c:import var="dataJson" url="http://localhost/request.json"/>
<json:parse json="${dataJson}" var="parsedJSON" />
Fetch the name of the node at index 1 : ${parsedJSON.node[1].name}
You can parse the input string to JSONValue and then cast it to JSONOject as like shown below
JSONObject inp = (JSONObject) JSONValue.parse(request.getParameter("param1"));
The svenson JSON library can also be used from JSP.
You've got several syntax errors in your example code.
First, request.getParameter returns a String, so setting it to a JSONObject won't work. Secondly, your for loop is incomplete.
I suggest looking into the various JSON libraries available for Java and using one of those.
To help get you started, I'd look at some decoding samples.
In general, you won't be passing JSON within query parameters -- too much quoting needed. Rather, you should POST with JSON as payload (content type 'application/json') or such.
But beyond this, you need a json parser; Json.org lists tons; my favorite is Jackson, which like most alternatives from the page can also be invoked from jsp.
Related
i'm using camel in a rest context and i've to manipulate a json got from a request . It's something like:
{
'field1':'abc',
'field2':'def'
}
All i've to do is to extract field1 and field2 and put them in 2 properties, so i tried something like that
<setProperty propertyName="Field1">
<jsonpath>$.field1</jsonpath>
</setProperty>
<setProperty propertyName="Field2">
<jsonpath>$.field2</jsonpath>
</setProperty>
but i get this error:
org.apache.camel.ExpressionEvaluationException:
com.jayway.jsonpath.PathNotFoundException: Expected to find an object with property ['field2'] in path $ but found 'java.lang.String'. This is not a json object according to the JsonProvider: 'com.jayway.jsonpath.spi.json.JsonSmartJsonProvider'.
and after some tests i found out my body was empty after the first use of jsonpath.
The same process applied to an XML using xpath doesn't give any error, and i'm wondering if it's possible to do the same with jsonpath instead to create a mapper object in java. thank you in advance
If the processed Camel message is of type InputStream, this stream can obviously be read only once.
To solve this:
either enable Camel stream caching (http://camel.apache.org/stream-caching.html)
or insert a step (before jsonpath queries) in your route to convert message body to a string (so that it can be read multiple times:
(eg <convertBodyTo type="java.lang.String" charset="ISO-8859-1">) )
I am building a Rest API using spring boot and Scala based on the below suggestion. I am successfully able to call the methods in Scala but the case class is not working the way it is designed.
When I try to create a Json using net.liftweb.json, I am getting additional string as "$outer":{}. I don't want this additional string in my output.
Note that the spring boot is expecting class instead of object. I suspect this could be an issue. Can you help me on this.
My case class looks like this:
case class BasicSrch(size: String, query: Match)
Erroneous output
{"$outer":{},"size":"10","query":{"$outer":{},"match":{"$outer":{},"_all":{"$outer":{},"query":"SNOW","operator":"and"}}}}
Expected Output
{"size":"10","query":{"match":{"_all":{"query":"VALLE","operator":"and"}}}}
If you are writing UTF-8 encoded JSON to the byte array or OutputStream then try jsoniter-scala: https://github.com/plokhotnyuk/jsoniter-scala
It will not serialize any other fields except those which are defined in a primary constructor of the case class.
I am very new to VBA and I can not figure out how to get values from a Collection.
This is my code:
Dim p As Object
Set p = JSON.parse(Response.Content)
Dim links As Object
Set links = p.Item("links")
In the debugger for "links" I see:
I am using this library to parse json : http://www.ediy.co.nz/vbjson-json-parser-library-in-vb6-xidc55680.html
The part I have in json is:
"links":[
{
"rel":"next",
"href":"www.google.com"
}
]
How can I get the value of "rel" here?
Don't forget the bang operator, designed for collection access by key:
links(1)!rel
or:
links(1)![rel] 'When there are spaces or reserved words.
I will answer my own question:
links(1).Item("rel")
worked...
Regards..
Using JavaScript features of parsing JSON, on top of ScriptControl, we can create a parser in VBA which will list each and every data point inside the JSON. No matter how nested or complex the data structure is, as long as we provide a valid JSON, this parser will return a complete tree structure.
JavaScript’s Eval, getKeys and getProperty methods provide building blocks for validating and reading JSON.
Coupled with a recursive function in VBA we can iterate through all the keys (up to nth level) in a JSON string. Then using a Tree control (used in this article) or a dictionary or even on a simple worksheet, we can arrange the JSON data as required.
You can see the full VBA code here
I am currently using a list of PropertyDTO s in my scala.html file to populate a view with Play2. The propertyDTO has a String attribute "value" which contains a JSON String. I want to convert this string to a JSON object in the scala.html file, and iterate through the JSON object collection. When trying the following,
val json = Json.parse(property.value),as[JsObject] within the scala code, it prints the expression. I would wish to know if my approach is correct, and if not , is there a suitable solution.
Code --> scala.html
#(propertyList : List[PropertyDTO])
#for(property <- propertyList){
#if(property.isInputProperty){
#if(property.propertyType=="BL"){
val json = Json.parse(property.value).as[JsObject]
}
}
}
I would not advise doing this in a template - the point of having templates, and not embedding HTML generation directly into your Scala code, is to separate the view logic from the application logic. If you go embedding Scala code like this in your template, then what's the point in using a template?
Best practice is to prepare all your data for rendering before calling the template, and then pass it into the template, and keep the template as dumb as possible, just iterating and rendering values.
The problem is that you need to declare code to be interpreted as scala code by putting an # in front of it. The line
val json = Json.parse(property.value).as[JsObject]
gets interpreted as HTML as there is no # sign in the line indicating scala code. What you can do is declare a whole block to contain scala code using #{ ... }.
For example you can store the result of your for comprehension in a variable for later use in the template:
#import play.api.libs.json._
#validPropertiesAsJson = #{
for{
property <- propertyList
if property.isInputProperty
if property.propertyType == "BL"
} yield Json.parse(property.value).as[JsObject]
}
And later in the template use #validPropertiesAsJson to include the value.
More information can be found in the playframework documentation: http://www.playframework.com/documentation/2.2.0/ScalaTemplates
Keep in mind to put as little logic into the template as possible.
I use Spring MVC.
I want to render some jsp by forwarding to it. And then I want to write the result to json.
For exmple I want to render my complex jsp and on exit I want to get:
{"result":"ok","html":"......."}
How can I do this?
I've tried to look at
request.getRequestDispatcher("tutorMini").forward(request, response)
But if I can't pass response to it, bcz it should write all output to it.
And I've tried to use some json tags in jsp, but it has some troubles with hierarchy:
HTML output with jsp:include and json-taglib
Since you need to apply additional conversion when inserting HTML into JSON (escape ' and "), you cannot write output of your JSP to the response directly.
So, you need to create an instance of ServletResponseWrapper that would save the output (by overriding getWriter() and/or getOutputStream()) and pass it to RequestDispatcher.include() (it looks more appropriate than forward() for this case):
MyServletResponseWrapper wrapper = new MyServletResponseWrapper(response);
request.getRequestDispatcher("tutorMini").include(request, wrapper);
String html = wrapper.getSavedOutput();
Then you can insert the saved content into JSON, escaping it appropriately.