Getting Data from Incoming Json in a Java Servlet

Getting data from incoming JSON in a Java servlet

I think the client send JSON data to you in the body of the request, not in a parameter. So the parameter that you try to parse as JSON data will be always null. To accomplish your task, you have first of all to get the body request and then parse it as JSON. For example, you can convert the body into a String with a method like this:

public static String getBody(HttpServletRequest request)  {

String body = null;
StringBuilder stringBuilder = new StringBuilder();
BufferedReader bufferedReader = null;

try {
InputStream inputStream = request.getInputStream();
if (inputStream != null) {
bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
char[] charBuffer = new char[128];
int bytesRead = -1;
while ((bytesRead = bufferedReader.read(charBuffer)) > 0) {
stringBuilder.append(charBuffer, 0, bytesRead);
}
} else {
stringBuilder.append("");
}
} catch (IOException ex) {
// throw ex;
return "";
} finally {
if (bufferedReader != null) {
try {
bufferedReader.close();
} catch (IOException ex) {

}
}
}

body = stringBuilder.toString();
return body;
}

So, your method will become:

@Override
public void doPut(HttpServletRequest request, HttpServletResponse response) {
// this parses the incoming JSON from the body.
JSONObject jObj = new JSONObject(getBody(request));

Iterator<String> it = jObj.keys();

while(it.hasNext())
{
String key = it.next(); // get key
Object o = jObj.get(key); // get value
System.out.println(key + " : " + o); // print the key and value
}
...

How to parse arraylist data sent from servlet into JSON in Jquery

You say this is what AJAX returns:

[INCOMING, 0, INETCALL, 0, ISD, 31.8, LOCAL, 197.92, STD, 73.2]

The strings are invalid for JSON; it should be:

["INCOMING", 0, "INETCALL", 0, "ISD", 31.8, "LOCAL", 197.92, "STD", 73.2]

Can't Deserialize JSON in Java Servlet

This might not be an ideal solution, but i do think it could work.

Hopefully you have the Jackson JSON dependency already...

you can find it here: http://mvnrepository.com/artifact/com.fasterxml.jackson.core/jackson-core

I would try the following code:

@POST
@Path("/{department}/{team}")
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
public Response handleJSON(String json, @PathParam("department") String department, @PathParam("team") String team){

ObjectMapper mapper = new ObjectMapper();
JsonNode node = mapper.readValue(json, JsonNode.class);

MyObj myObj = new MyObj();

myObj.setDepartment(department);
myObj.setTeam(team);

if (node.get("platform") != null) {
myObj.setPlatform(node.get("platform").textValue());
}

saveObj(myObj);

return Response.ok(true).build();

}

Notice that I am asking your WS Framework to just pass me the JSON as a String and just handling it myself.
Maybe its not ideal, but should work.

Cheers!

How to receive compressed JSON data using XMLHttpRequest from a java server

In this case, the same data sets are being served repeatedly to clients. Rather than adding a jetty handler, the json text string is converted to a gzipped byte array:

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.nio.charset.StandardCharsets;
import java.util.zip.GZIPOutputStream;

ByteArrayOutputStream bos = new ByteArrayOutputStream();
GZIPOutputStream gzip = new GZIPOutputStream(bos);
OutputStreamWriter osw = new OutputStreamWriter(gzip, StandardCharsets.UTF_8);
osw.write(myDataInJsonStringFormat);
osw.close();

compressedJsonData = bos.toByteArray();

The data is then returned to the java client by the jetty handler:

public void handle(String target, Request baseRequest, HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {

response.setContentType("application/json");
response.setHeader("Content-Encoding", "gzip");
response.setContentLength(compressedJsonData .length);

response.setStatus(Response.SC_OK);

response.getOutputStream().write(compressedJsonData );
response.getOutputStream().close();

baseRequest.setHandled(true);
}

In the XMLHttpRequest javascript code on the client side no change is necessary. Browsers (verified on Edge, IE11, Chrome) automatically decompress the json and convert it back to text before passing it to this.responseText :

var http = new XMLHttpRequest();
http.onreadystatechange=function() {
if (this.readyState == 4) {
if (this.status == 200) {
data = JSON.parse(this.responseText);
}
}
};
http.open("GET", "/mydata", true);
http.send();

I also added a progress bar to show a client how much data has been downloaded. For this the length prior to compression is saved and added as a custom http header on the server side

response.setHeader("Uncompressed-Length", myDataInJsonStringFormat.length + "");

On the client this header is read in the onreadystatechange handler as estimatedLength when readyState == 2 and a progress handler set up as follows:

    http.onprogress = function(event) {
var percentComplete = Math.round((event.loaded/estimatedLength) * 100);
progressMessage = Math.round(event.loaded/1000) + "KB downloaded and uncompressed, " + percentComplete + "%";
};

Getting values from external API and displaying through another controller

If you don't want to use a database, then your other option is to store the date in memory as follows:

@RestController
public class Controller1 {

private Service service;

public Controller1(Service service) {
this.service = service;
}

@GetMapping(value = "/test")
public List<Object> getdata() {
return service.getData();
}
}

Your Controller would rely on a Service to get the data from another API as follows:

@Service
public class Service {

private List<Object> data = new ArrayList<>();

public List<Object> getdata() {
String e_url = ""; //external API with above JSON data
RestTemplate rt = new RestTemplate();
Object[] test = rt.getForObject(e_url,Object[].class);
data = Arrays.asList(test);
return data;
}

public List<Object> getRetrievedData() {
return data;
}
}

Now, in your Controller2 you could get the retrieved data from the Service:

public class controller2 extends HttpServlet {

private Service service; // Not really sure how to inject this here since for whatever
// reason you are using an `HttpServlet` instead of a regular Spring Boot Controller

Public void doGet(HttpServletRequest request, HttpServletResponse response) throwsServletException {}
Public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException {
service.getRetrievedData();
}
Public static void pr(HttpServletRequest request, HttpServletResponse response, PrintWriter out) {
//From here I want to display the JSON data to web interface which passes from controller 1
}
}


Related Topics



Leave a reply



Submit