Write json object with controller using rendered jsp - json

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.

Related

prepend a string in all responses within ASP.NET core json

I would like to prepend all JSON responses with following string:
)]}',\n
What is the best way to achieve this with ASP.NET Core? I would like to have it enabled for all JSON responses automatically.
You could use a Middleware that checks the following condition (or whatever condition you need).
if(context.Response.ContentType == "application/json")
Then you just append prepend the context.Response.Body with your string.

Matching the Json schema with the response getting from the API in rest-assured

I have a post API , i want methods of JsonSchemaValidator to be used as I want the whole reponse to be validated rather than selected reponse by performing assertion
I have tried to use
matchesJsonSchemaInClasspath("my file name") and
matchesJsonSchema(my file object)
my reposne is coming to be true, method is getting passed but there is no checking or validation with my schema file
public void directLoginWihSchemaValiadtor(){
File file = new File("C:/Users/abeey/git/SlingAppWebService/Configurations/JsonSchemaValidator_DirectLogin_AWS.json");
jsonasmap.put("contactNo", "some number");
jsonasmap.put("loginType","0");
jsonasmap.put("appid","2");
jsonasmap.put("co*****ode","IN");
JsonSchemaFactory jsonSchemaFactory = JsonSchemaFactory.newBuilder().
setValidationConfiguration(ValidationConfiguration.newBuilder().freeze()).freeze();
given().contentType(ContentType.JSON).body(jsonasmap).when().
post("https://60i*****.execute-api.us-west-2.amazonaws.com/some-api").
then().assertThat().
body(JsonSchemaValidator.matchesJsonSchema(file))).
log().all();
jsonasmap.clear();
}
//body(JsonSchemaValidator.matchesJsonSchemaInClasspath("JsonSchemaValidator_DirectLogin_AWS.json").using(jsonSchemaFactory))
I tried to use jsonSchemaFactory to do this but i didnt get that either on what to set as the draftversion or from where to get it
I am new to this , please bear with me if you found this question too simple to be asked
For such case usually I do following:
use schema generator and create the schema for json body (I use this tool json-schema-generator)
put generated json schemas in the classpath (for example test/resources)
use this code as part of REST Assured test:
.body(matchesJsonSchemaInClasspath("your_schema_name.json"))
If you want to make sure that schema validation is working, you can edit schema file and change the type of any required field to something else and see that your test will fail.
You can refer to this post of mine to see some code samples.

Convert a String to JSON in scala.html file

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.

Create a List-type view dynamically from a Json object in MVC3

I have a controller that access a WCF service which returns a Json object (collection). All rows are of same type, but at different calls the row stricture is different (the return object comes from a user-built sql query, executed with executeReader and serialized as Json
So I don't know the row structure upfront.
What I need is an easy way to pass this Json string to something which will generate a view of type list on the fly for it. Doesn't matter formatting, etc, just should be output easily as a table.
Does anyone knows how can I accomplish this?
Another option might be to have something that generate the view on the fly for a IEnumerable of anonymous objects (since using this I could convert the json to a list of anonymous)
EDIT
I found something that does pretty much what I need, except it display metadata about passed object.
It is preetyPrint.js, and I integrated it in my page as below:
In my controller I set the result json object to ViewBag.Result, and in the view I used this code:
<script src="#Url.Content("~/Scripts/prettyprint.js")" type="text/javascript"> </script>
<div id="resultGrid"></div>
<script>
var resultObject = #Html.Raw(ViewBag.Result);
var ppTable = prettyPrint(resultObject);
document.getElementById('resultGrid').appendChild(ppTable);
</script>
Does anyone knows such script that actually "dump" the data instead of metadata?
Thanks.
You should create a class to deserialize to if you know the properties of the row. Then use the JavaScriptSerializer class to deserialize to a list of your new class you created. Then you can take a look at the WebGrid class to output the HTML, or just manually iterate over the property metadata in your view.
Creating a custom class will provide you the ability to use metadata to control formatting or other display attributes of the output.
If you cannot create a custom class, you can always use Json.NET or the JavaScriptSerializer to deserialize to a list of dictionary objects or ExpandoObject / Dynamic's or something. Then you would have to manually write something to iterate the keys I think. The ModelMetadataProvider in MVC may be able to handle these allowing you to just iterate the properties in your view code.

Processing json objects in jsp

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.