I'm making an inventory control. I was trying to check if the entered quantity of item is less than the stock quantity or not. I'm getting the servet json output. But I can't send it to jsp back.
Jsp JQuery code.
<script>
$('document').ready(function() {
$('#submit_btn').click((function() {
var $name = $("select#item_name").val();
var $qty = $("input#qty").val();
$.post('BuyItem', {item_name: $name, item_qty: $qty}, function(data) {
if (data !== null) {
alert(text(data));
$("input#qty").val("");
} else {
alert("Invalid Item!");
}
}
);
}));
});
</script>
And this is servlet query.
while (rs.next()) {
if (rs.getInt("qty") > qty) {
int id = rs.getInt("item_id");
Gson gson = new Gson();
String json = gson.toJson(id);
// System.out.println("one" + json);
response.setContentType("application/json");
// response.setCharacterEncoding("UTF-8");
response.getWriter().print(json);
} else {
Gson gson = new Gson();
String json = gson.toJson("Stock doesn\'t have enough item quantity.");
// System.out.println("two" + json);
response.setContentType("application/json");
// response.setCharacterEncoding("UTF-8");
response.getWriter().print(json);
}
}
From both System.out.println() s output is always coming correctly. But not sending to jsp back. Please help me with this.
what you have to do and also a best practice is to create a DTO class with the properties that you need to pass to gson library.
public class ResponseDTO implements Serializable{
private Integer id;
//more properties ...
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id= id;
}
// other getters & setters
}
and inside your loop, set the values to the dto object, then pass it to gson.
Gson gson = new Gson();
ResponseDTO dto = null;
String json = "";
response.setContentType("application/json");
......
if (rs.getInt("qty") > qty) {
dto = new ResponseDTO();
int id = rs.getInt("item_id");
dto.setId(id);
......
json = gson.toJson(dto);
} else {
...... // similar
json = gson.toJson("{data: 'Some message'}");
}
response.getWriter().print(json);
gson will give you the proper json structure to the client side.
try and see !
Gson allows strings and numbers to serialize to JSON by themselves (which is probably ok by the definition), but a lot of other libraries would consider this invalid JSON.
Try wrapping your response in an object so that the response is {"id": 5} and not just 5.
Related
I'm presently migrating from the Java ASK-SDK v1 to Java ASK SDK v2.
I'm trying to return a webhook call using the ResponseBuilder class that I built my response up and the data is correct, however when I try to populate the HTTP body with the JSON text, the ResponseBuilder.toString() value doesn't just populate the data with just the string, I get the following:
Optional[class Response {
outputSpeech: class SsmlOutputSpeech {
class OutputSpeech {
type: SSML
playBehavior: null
}
ssml: <speak>Some of the things you can say are What would you like to do?</speak>
}
card: null
reprompt: class Reprompt {
outputSpeech: class SsmlOutputSpeech {
class OutputSpeech {
type: SSML
playBehavior: null
}
ssml: <speak>You can say ..., is that what you want?</speak>
}
}
directives: []
shouldEndSession: false
canFulfillIntent: null
}]
Is there another way to get the string for the body of the response? The BaseSkillResponse has a getResponse() call, however, I cannot figure out how to use the class to generate the String response output.
I was able to get the string with the following in my class:
private static final ObjectMapper OBJECT_MAPPER = new ObjectMapper();
myFunction(){
try{
return toJsonString(responseBuilder.build().get());
} catch(IOException e) {
e.printStackTrace();
}
}
public String toJsonString(Response response)throws IOException {
return OBJECT_MAPPER.writeValueAsString(response);
}
Solve this by doing the following:
public String toJsonString(Response response)throws IOException
{
JacksonSerializer jacksonSerializer = new JacksonSerializer();
constructedResponse = jacksonSerializer.serialize(response);
JSONObject jsonObject = new JSONObject();
jsonObject.put("response",constructedResponse);
}
I am developing a rest server in java, netbeans.
I have my GET request:
//myip/application/v1/cardapio/id=1
#Stateless
#Path("v1/cardapio")
public class CardapioResource {
#GET
#Produces("application/json")
#Path("id={id}")
public String getCardapio(#PathParam("id") int id) {
JsonArray array = (JsonArray) gson.toJsonTree(ejb.findById(id));
JsonObject obj = new JsonObject();
obj.add("dados", array);
return obj.toString();
}
}
It works correctly.
But I want to do differently, as I saw in other examples, I want to mark the beginning of the variables with the "?".
Ex: //myip/application/v1/cardapio/?id=1
#Stateless
#Path("v1/cardapio")
public class CardapioResource {
#GET
#Produces("application/json")
#Path("?id={id}")
public String getCardapio(#PathParam("id") int id) {
JsonArray array = (JsonArray) gson.toJsonTree(ejb.findById(id));
JsonObject obj = new JsonObject();
obj.add("dados", array);
return obj.toString();
}
}
Thus error 404, page not found.
What you seen in "other examples" is just normal usage of URL's query part. Just use it with #Queryparam
#Stateless
#Path("v1/cardapio")
public class CardapioResource {
#GET
#Produces("application/json")
#Path("/") // can be removed actually
public String getCardapio(#QueryParam("id") int id) {
JsonArray array = (JsonArray) gson.toJsonTree(ejb.findById(id));
JsonObject obj = new JsonObject();
obj.add("dados", array);
return obj.toString();
}
}
Here you are mapping getCardapio to v1/cardapio/ and you will try to get id from query string so
Ex: //myip/application/v1/cardapio/?id=1
will just work.
You can't, after ? sign it's query parameters and not path parameters
You can use #QueryParam("id")
You can also use
#RequestParam("id") int id
Android space
void post(Food food)
{
Gson gson = new Gson();
String jsonFood = gson.toJson(food);
RestTemplate restTemplate = new RestTemplate();
restTemplate.getMessageConverters().add(new MappingJackson2HttpMessageConverter());
restTemplate.postForEntity(URL, jsonFood, String.class);
}
Back end space
#PostMapping("/food")
public void postFood(#RequestBody String foodJson)
{
Food food = new GsonBuilder().create().fromJson(foodJson, Food.class);
String id = createId(food);
// now how do I send back saying I got this and here is an id?
}
After I receive I want to reply back saying I got the information and send back an ID.
Spring boot will automatically convert the json to a model object under the covers using Jackson
#PostMapping("/food")
public YourResponse postFood(#RequestBody Food food)
{
String id = createId(food);
return new YourResponse(id,"hello World");
}
Response object
public class YourResponse{
private String id;
private String response;
//.. constructor, getter setter
}
You can create a response model
public class PostFoodResponse{
private String id;
private String response;
//.. constructor, getter setter
}
In your code create an object of PostFoodResponse set data and send the object back as a json response
#PostMapping("/food")
public String postFood(#RequestBody String foodJson)
{
Food food = new GsonBuilder().create().fromJson(foodJson, Food.class);
String id = createId(food);
// now how do I send back saying I got this and here is an id?
PostFoodResponse response = new PostFoodResponse(id, "I got this");
return new GsonBuilder().create().toJson(response);
}
I need to send data to database in this format -
{"param1":"value1", "param2":"value2", "param3": {"username": "admin", "password": "123"}}
How to generate this using JSONStringer ?
I tried this -
vm = new JSONStringer().object().key("param1").value("value1")
.object().key("param2").value("value2")
.key("param3").object()
.key("username").value("admin")
.key("password").value("123")
.endObject().endObject().endObject();
But I'm getting this error -
org.json.JSONException: Nesting problem at
org.json.JSONStringer.beforeValue(JSONStringer.java:415)
JSONObject object1 = new JSONObject();
object1.put("param1", "value1");
object1.put("param2", "param2");
JSONObject innerObject1 = new JSONObject();
innerObject1.put("username", "admin");
innerObject1.put("password", "123");
object1.put("param3",innerObject1);
String jsonStr = object1.toString();
Ideally reverse of JSON parsing can be applied to create a json string object, so that the same can be send to Server/DB
Try this
try {
JSONObject object=new JSONObject();
object.put("param1","value1");
object.put("param2","value2");
JSONObject param3=new JSONObject();
paraam3.put("username","admin");
paraam3.put("password","123");
object.put("param3",param3);
} catch (JSONException e) {
e.printStackTrace();
}
You can create model which will be your java file same as your JSON file and can use gson library which is supported by Google to do JSON parsing. The library is quite flexible and easy to use then using traditional method of JSON parsing.
Model File
public class Response {
public String param1;
public String param2;
public Param3 param3;
public Response(String param1, String param2) {
this.param1 = param1;
this.param2 = param2;
}
public class Param3 {
public String username;
public String password;
public Param3(String username, String password) {
this.username = username;
this.password = password;
}
}
}
In file in which you insert data
Response res = new Response("value1", "value2", new Param3("admin","123"));
String dbResult = new Gson.toJson(res);
If you are looking for the actual solution using org.json.JSONStringer
JSONWriter writer = stringer3.object()
.key("param1").value("value1")
.key("param2").value("value2")
.key("param3").object()
.key("username").value("admin")
.key("password").value("123")
.endObject()
.endObject();
System.out.println(writer.toString());
You can think of the object() method as opening a new parenthesis and the endObject() as closing it
I am using Spring MVC and returning JSON as response. I would like to create a generic JSON response where I can put in any TYPE and want the response to look like this
{
status : "success",
data : {
"accounts" : [
{ "id" : 1, "title" : "saving", "sortcode" : "121212" },
{ "id" : 2, "title" : "current", "sortcode" : "445566" },
]
}
}
So I created a Response<T> object
public class Response<T> {
private String status;
private String message;
T data;
...
...
}
Is this the correct way of doing this, or is there a better way?.
How do you use this Response object in Spring controller to return an empty response object and/or a populated response object.
Thanks in advance GM
UPDATE:
In order to get the similar JSON output as the one described, i.e. with "accounts" key in JSON, I had to use Response<Map<String, List<Account>>> the following in the controller:
#RequestMapping(value = {"/accounts"}, method = RequestMethod.POST, produces = "application/json", headers = "Accept=application/json")
#ResponseBody
public Response<Map<String, List<Account>>> findAccounts(#RequestBody AccountsSearchRequest request) {
//
// empty accounts list
//
List<Account> accountsList = new ArrayList<Account>();
//
// response will hold a MAP with key="accounts" value="List<Account>
//
Response<Map<String, List<Account>>> response = ResponseUtil.createResponseWithData("accounts", accountsList);
try {
accountsList = searchService.findAccounts(request);
response = ResponseUtil.createResponseWithData("accounts", accountsList);
response.setStatus("success");
response.setMessage("Number of accounts ("+accounts.size()+")");
} catch (Exception e) {
response.setStatus("error");
response.setMessage("System error " + e.getMessage());
response.setData(null);
}
return response;
}
Is this the right way of doing this? i.e. in order to get the "accounts" key in JSON output?
While your example JSON is not valid (status and data are not enclosed in quotations), this approach will work.
You will want to ensure that you have the Jackson jars on your classpath, and Spring will take care of the rest.
To get this to work, I would create a constructor for your response class that looks something like this:
public class Response<T> {
private String status;
private String message;
private T data;
public Response(String status, String message, T data) {
this.status = status;
this.message = message;
this.data = data;
}
//...getter methods here
}
And then in your Spring controller, you just return this object from your method that is mapped with #RequestMapping
#Controller
public class MyController {
#RequestMapping(value="/mypath", produces="application/json")
public Response<SomeObject> myPathMethod() {
return new Response<SomeObject>("200", "success!", new SomeObject());
}
}