JSON, Servlet, JSP - json

Firstly, my HTTP POST through a URL accepts 4 parameters. (Param1, Param2, Param3, Param4).
Can I pass the parameters from the database?
Once the URL is entered, the information returned will be in text format using JSON
format.
The JSON will return either {"Status" : "Yes"} or {"Status" : "No"}
How shall I do this in servlets? doPost()

Just set the proper content type and encoding and write the JSON string to the response accordingly.
String json = "{\"status\": \"Yes\"}";
response.setContentType("application/json");
response.setCharacterEncoding("UTF-8");
response.getWriter().write(json);
Instead of composing the JSON yourself, you may consider using an existing JSON library to ease the job of JSON (de)serializing in Java. For example Google Gson.
Map<String, String> result = new HashMap<String, String>();
result.put("status", "Yes");
// ... (put more if necessary)
String json = new Gson().toJson(result);
// ... (just write to response as above)

Jackson is another option for JSON object marshalling.

Related

How to post values from RestAssured to JSon and get a value from it?

{"service_request": {"service_type":"Registration","partner":"1010101","validity":1,"validity_unit":"Year","quantity":1,"center":"1020301","template":"2020301"}}
I have JSON values as above obtained from Request Payload, when I post data from the web page. I want to post this data from RESTAssured in java and want to get the returned value? How can I do that?
I would recommend to check https://github.com/jayway/rest-assured/wiki/Usage#specifying-request-data
I imagine you are trying to do a POST using Rest-Assured.For that simplest and easy way is.. Save your payload as String. If you have payload as JSONObject, use toJSONString() to convert it to String
String payload = "yourpayload";
String responseBody = given().contentType(ContentType.JSON).body(payload).
when().post(url).then().assertThat().statusCode(200).and()
extract().response().asString();
Above code, post your payload to given Url, verify response code and convert response body to a String. You can do assertion without converting to String as well like
given().contentType(ContentType.JSON).body(payload).
when().post(url).then().assertThat().statusCode(200).
and().assertThat().body("service_request.partner", equalTo("1010101"));

Jettison can not convert json string to json object when there is an element has empty string value

My application is using camel rest (2.15.2) to catch a POST json String and then uses jettison to convert to a JSON Object. It is working fine with normal request.
POST request: {"request"={"lname"="aaa", "fname"="bb"}}
1. String body = exchange.getIn().getBody(String.class);
2. JSONObject obj = new JSONObject(body);
When i debug, variable body = {request={lname=aaa, fname=bb}}.
And line 2 returns a JSONObject. so far so good
if we try to another the request:
{"request"={"lname"=" ", "fname"="aa"}}
then body = {request={lname= , fname=aa}}
line2 returns Exception.
Could you please help me to fix this issue: convert json string which contains element has empty value string to json object.
The above request is acceptable in my scenarios.
Error:
org.codehaus.jettison.json.JSONException: Missing value. at character
15 of {request={lname= , fname=aa}} at
org.codehaus.jettison.json.JSONTokener.syntaxError(JSONTokener.java:463)
at
org.codehaus.jettison.json.JSONTokener.nextValue(JSONTokener.java:356)
at org.codehaus.jettison.json.JSONObject.(JSONObject.java:230)
at
org.codehaus.jettison.json.JSONTokener.newJSONObject(JSONTokener.java:412)
at
org.codehaus.jettison.json.JSONTokener.nextValue(JSONTokener.java:327)
at org.codehaus.jettison.json.JSONObject.(JSONObject.java:230)
at org.codehaus.jettison.json.JSONObject.(JSONObject.java:311)

How can I define a ReST endpoint that allows json input and maps it to a JsonSlurper

I want to write an API ReST endpoint, using Spring 4.0 and Groovy, such that the #RequestBody parameter can be any generic JSON input, and it will be mapped to a Groovy JsonSlurper so that I can simply access the data via the slurper.
The benefit here being that I can send various JSON documents to my endpoint without having to define a DTO object for every format that I might send.
Currently my method looks like this (and works):
#RequestMapping(value = "/{id}", method = RequestMethod.PUT, consumes = MediaType.APPLICATION_JSON_VALUE)
ResponseEntity<String> putTest(#RequestBody ExampleDTO dto) {
def json = new groovy.json.JsonBuilder()
json(
id: dto.id,
name: dto.name
);
return new ResponseEntity(json.content, HttpStatus.OK);
}
But what I want, is to get rid of the "ExampleDTO" object, and just have any JSON that is passed in get mapped straight into a JsonSlurper, or something that I can input into a JsonSlurper, so that I can access the fields of the input object like so:
def json = new JsonSlurper().parseText(input);
String exampleName = json.name;
I initially thought I could just accept a String instead of ExampleDTO, and then slurp the String, but then I have been running into a plethora of issues in my AngularJS client, trying to send my JSON objects as strings to the API endpoint. I'm met with an annoying need to escape all of the double quotes and surround the entire JSON string with double quotes. Then I run into issues if any of my data has quotes or various special characters in it. It just doesn't seem like a clean or reliable solution.
I open to anything that will cleanly translate my AngularJS JSON objects into valid Strings, or anything I can do in the ReST method that will allow JSON input without mapping it to a specific object.
Thanks in advance!
Tonya

RestSharp: get JSON string after deserialization?

using RestSharp is there a way to get the raw json string after it has been deserialized into an object? I need that for debugging purposes.
I'd like to see both the deserialized object and the originally received json string of that object. It's part of a much bigger json string, an item in an array and I only need that specific item json code that's got deserialized into the object.
To help you out this should work, this is a direct example of some of my work, so your's might be a bit different.
private void restClient()
{
string url = "http://apiurl.co.uk/json";
var restClient = new RestClient(url);
var request = new RestRequest(Method.GET);
request.AddParameter("apikey", "xxxxxxxxxx");
restClient.ExecuteAsync<Entry>(request, response =>
{
lstboxtop.Items.Add(response.Content);
});
}
The line lstboxtop is a listbox and using the response.content will literally print the whole api onto your app, if you call it first that would be what you are looking for

difference between json string and parsed json string

what is the difference between json string and parsed json string?
for eg in javascript suppose i have a string in the json format say [{},{}]
parsing this string will also produce the same thing.
So why do we need to parse?
It's just serialization/deserialization.
In Javscript code you normally work with the object, as that lets you easily get its properties, etc, while a JSON string doesn't do you much good.
var jsonobj = { "arr": [ 5, 2 ], "str": "foo" };
console.log(jsonobj.arr[1] + jsonobj.str);
// 2foo
var jsonstr = JSON.stringify(jsonobj);
// cannot do much with this
To send it to the server via an Ajax call, though, you need to serialize (stringify) it first. Likewise, you need to deserialize (parse) from a string into an object when receiving JSON back from the server.
Great question. The difference is transfer format.
JSON is only the 'Notation' of a JavaScript Object, it is not actually the JavaScript 'object-literal' itself. So as the data is received in JSON, it is just a string to be interpreted, evaluated, parsed, in order to become an actual JavaScript 'Object-Literal.
There is one physical difference between the two, and that is quotation marks. It makes sense, that JSON needs to be a string to be transferred. Here is how:
//A JavaScript Object-Literal
var anObj = { member: 'value'}
//A JSON representation of that object
var aJSON = { "member":"value" }
Hope that helps. All the best! Nash
I think a parsed json string should be the string data into the actual javascript objects and data arrays (or whichever language the json string contains)
The JSON object contains methods for parsing JSON and converting values to JSON.
It can't be called or constructed, and aside from its two method properties it has no interesting functionality of its own.
JSONParser parser = new JSONParser();
Object object = parser.parse(Message.toString());
JSONObject arObj = (JSONObject) object;