Consume XML in Java with Jersey - java

I've build a web application that produces XML code of an object. To my suprise, the xml produced is completely correct and in the format I wanted it. However, I'm now making a method that consumes XML in the same format and turn it back in an object. How can I test if it is working?
I've tried using a REST extension in chrome that posts the exact same XML that my other method produces, but I get the error: "The server refused this request because the request entity is in a format not supported by the requested resource for the requested method." I've also tried putting breakpoints in my code and debugging it that way, but my breakpoints are never even reached.
#GET
#Produces(MediaType.TEXT_XML)
public week_program getXml() {
week_program weekProgram = new week_program();
return weekProgram;
}
#POST
#Consumes(MediaType.TEXT_XML)
public Response PostXml(week_program weekProgram) {
System.out.println(weekProgram);
return Response.status(Status.OK).entity(weekProgram).build();
}
How can I fix it, or even test correctly if it does actually work?

I would suggest using json instead of XML and Gson from Google.
Since json output is usually smaller than XML (fat free).
Object to JSON
DataObject obj = new DataObject();
Gson gson = new Gson();
String json_string = gson.toJson(obj);
JSON to Object
DataObject obj = gson.fromJson(json_string, DataObject.class);
Here's a tutorial. http://www.mkyong.com/java/how-do-convert-java-object-to-from-json-format-gson-api/

Related

Best way to send a JSon object from Servlet

The question can seem simple, but I didn't find a good answer yet. I need to send a JSon structure (build with an unspecified libretry I'm currently developing) from a Servlet to a remote page.
I'm interested in the best way to send the structure.
I mean, in my Servlet, inside the doPost() event, how should I manage the send?
I was thinking about 2 scenarios:
try (PrintWriter out = response.getWriter()) {
out.print(myJSon.toString(); // <- recursive function that overrides
// toString() and returns the entire JSon
// structure
} (...)
or
try (OutputStream os = response.getOutputStream()) {
myJSon.write(os, StandardCharsets.UTF8); // <- function that
// recursively writes chunk of my JSon structure
// in a BufferWriter created inside the root write function
// forcing UTF-8 encoding
} (...)
Or something different, if there's a better approch.
Note that the JSon structure contains an array of objects with long text fields (descriptions with more than 1000 characterd), so it can be quite memory consuming.
For why I'm not using standard JSon libreries, it's because I don't know them and I don't know if I can trust them yet. And also I don't know if I will be able to install them on the production server.
Thanks for your answers.
From your question i see multiple points to adress:
How to send your JSon
What JSon library can you use
How to use the library in production
How to send your JSon
From your code this seems to be an HTTP response rather than a POST on your Servlet so you need to know how to send a JSON string as an HTTP response's body
Do you use a framework for your web server or are you handling everything manually ? If you use a framework it usually does it for you, just pass the JSON String
If your doing it manually:
try (PrintWriter pw = response.getWriter()) {
pw.write(myJson.toString());
}
or
try (OutputStream os = response.getOutputStream()) {
os.write(myJson.toString().getBytes());
}
Both are valid, see Writer or OutputStream?
Your JSON's size shouldn't matter given what your saying, it's just text so it won't be big enough to matter.
What libraries can you use
There are a lot of JSON libraries for Java, mainly:
Jackson
GSon
json-io
Genson
Go for the one you prefer, there will be extensive documentation and resources all over google
How to use in production
If you are not sure you are able to install dependencies on the production server, you can always create an uber-jar (See #Premraj' answer)
Basically, you bundle the dependency in your Jar
Using Gson is good way to send json
Gson gson = new Gson();
String jsonData = gson.toJson(student);
PrintWriter out = response.getWriter();
try {
out.println(jsonData);
} finally {
out.close();
}
for detail json response from servlet in java

twitter4j 4.0.2 getRawJSON() returns null

I'm trying to save the tweets I got as JSON objects and however still unable to get the JSON object out of Status objects.
I have checked JSONStoreEnabled() and it's set to true.
API says,
Note that raw JSON forms can be retrieved only from the same thread
invoked the last method call and will become inaccessible once another
method call.
I have my everything inside the main() method, so I guess this shouldn't be an issue.
String tweet = TwitterObjectFactory.getRawJSON( status );
I have checked that the status object contains all the information and it's just that getRawJSON returns null!.
Really appreciate if someone can tell me a fix for this.
I am using this approach in my own app. You can try this while configuring Twitter4j.
Using com.google.gson.Gson;
public Gson gson = new Gson();
ConfigurationBuilder config = new ConfigurationBuilder();
config.setJSONStoreEnabled(true);
config.setOAuthConsumerKey(Keys.TWITTER_KEY);
config.setOAuthConsumerSecret(Keys.TWITTER_SECRET);
config.setOAuthAccessToken(currentSession.getAuthToken().token);
config.setOAuthAccessTokenSecret(currentSession.getAuthToken().secret);
Configuration cf = config.build();
// For Twitter4j
enter code here
String statusJson = TwitterObjectFactory.getRawJSON(status); // status to json
This is it.
Gson gson = new Gson();
String json = gson.toJson( status );
System.out.println( json );
new twitter4j.JSONObject(status)
it is works for me

Extjs file upload and return message using JSONObject

I tried uploading an excel file and it worked well but the return message doesn't show. For the return message I use the below code as shown here:
JSONObject myObj = new JSONObject();
//sets success to true
myObj.put("success", true);
//convert the JSON object to string and send the response back
out.println(myObj.toString());
out.close();
For using this class I used the json-lib.jar. Further it asks for dependent jars like ezmorph-1.0.jar which I am doubtful of using.
Has anyone used the above method to return a message to the front end?
If so, what were the jars used in the process? Please help
I resolved the above by using json-simple-1.1.jar instead of json-lib.jar.
This created a JSONObject without the need of any other jar.

Parsing json response using play libs

I need to parse json response in a play application and get all the fields/values in a list.
I'm getting the response as below:
WSRequestHolder request = WS.url("someurl");
request.setQueryParameter("somekey", "somevalue");
Promise<Response> promise = request.get();
Response response = promise.get();
JsonNode json = response.asJson();
The response comes like below:
{"results":{"key1":value1,"key2":value2,"key3":value3},"errorMessage":"","statusCode":2000,"success":true,"version":"1.01"}
I need to get all the feilds/values from "results" list. How can i do this using play json libraries / apis available? I'm using play 2.1.1.
Thanks.
Since the result is a JsonNode, you have all the niceties of JsonNode available to you.
For instance, if you want to access "results", do:
JsonNode results = json.get("results");
You also have methods such as .has(), .path(), .entries(), etc etc. One JsonNode can represent any JSON value, including null.
To test the type you can use the .is*() methods: .isObject(), .isNumber(), .isMissing() (note: the latter requires the use of .path() instead of .get()).
Example:
json.path("foo").isMissing(); // true
json.path("errorMessage").getTextValue(); // ""
json.get("results").get("key2"); // value2
json.get("success").getBooleanValue(); // true
Etc etc. See the javadoc for JsonNode.
Another solution would be to deserialize that JSON into a POJO. But that means creating the POJO in the first place, and then use an ObjectMapper to .read*() the value.
(side note: it is surprising that Play uses Jackson 1.9.x whereas 2.0+ has been available for many years...)

GSON Can I convert only part of JSON, the ones I want Using GSON.fromJSON()

I am working with a big JSON object which has responses form multiple requests.
And the part I am working on requires only few object and they are not always in front.
For Example the json structure is:
**
json = {
mainDocument: {
element1: {
element11: "value11",
element12: {
element121: "value121"
}
},
element2: {
element21: {
element211: {
element2111: "value2111",
element2112: {
element21121: "value21121"
}
}
},
element22: "value22"
}
}
}
**
This structure can change depending on whether or not the request is successful.
Now,
I want to create an java object with the value of element11, element 22, element21121.
Currently I just check the json and use the setters of the object.
I want to know if there is a way to let GSON handle this and not have to parse the json myself.
Thanks in advance for any help you can offer.
I don't know if I understand your question very well, but in order to deserialize a JSON response with Gson, the most proper way in my opinion is to create a class structure that encapsulates the data in the response. In your case something like:
class Response
MainDocument mainDocument
class MainDocument
Element element1
Element element2
class Element
...
If you only need some data from the JSON, you can omit attributes in your class structure and Gson will ignore them. And if an object can have different contents in different responses, you can have something like this:
class Response
MainDocument mainDocument
Error error
And Gson will parse responses both with a root element mainDocument (like the one in the question) or with a root element error... this allows you to adapt your parsing to variable responses...
Obviously, to follow this approach, you need to know all the possible response structures you can have. If your problem is that your JSON response is absolutely variable, and you cannot create a class struture to wrap it, you always could do a manual parsing, somehting like this:
JsonParser parser = new JsonParser();
JsonObject rootObj = parser.parse(jsonString).getAsJsonObject();
String element21121 = rootObj
.getAsJsonObject("mainDocument")
.getAsJsonObject("element2")
.getAsJsonObject("element21")
.getAsJsonObject("element211")
.getAsJsonObject("element2112")
.getAsString("element21121");

Categories