How To Extract Data From JSON with Rest Template in Java - java

i have to extract the first 5 articles from https://newsapi.org/v2/top-headlines?sources=bbc-news&apiKey=19acc3a371d145ecb37a093f9985ea21, having a result like this:
{
"total": 5,
"articles": [
{
"source": "Ilmessaggero.it",
"title": "Title",
"author": "Author",
"url": "URL"
}
]
}
I did this, having all the JSON as String as output for the localhost...
#RequestMapping("/news")
public Article connection() {
return restTemplate.getForObject
("https://newsapi.org/v2/top-headlines?sources=bbc-news&apiKey=19acc3a371d145ecb37a093f9985ea21", Article.class);
The result in the localhost is:
{"source":null,"title":null,"author":null,"url":null}
But the problem now is, how do i put the data into the list of articles?
and how do i save them into mongodb? thanks for the effort

I solved it! SImply, the NewsAPI json of Article has a field called Source, which i was trying to parse as a string, but it was NOT! Infact, it is a field described with another object! I simply had to create a class called Source with id and name, and it works! Thanks everyone for the effort!
Here's the codes of the classes:
public class Article {
private Source source;
private String author;
private String title;
private String url;
//getters and setters
News, which has a list of articles:
public class News {
private int totalResults;
private List<Article> articles;
//getters and setters
And source, which is called in Article:
public class Source {
private String id;
private String name;
//getters and setters
Here it is! The parse code is the same of the answer. Just change the return type (Article) as News and the Article.class parameter of getForObject into News.class

A simple (i.e. missing exception handling, etc) way is as follows:
First, you need a class to represent the data you are receiving, with fields that match the API response fields, for example:
public class Article {
private String source;
private String title;
... // more fields
// getters and setters
}
The code to fetch the data from the API then looks like this:
RestTemplate template = ... // initialized earlier
ResponseEntity<Article[]> response = template.exchange(
API_URL, // url to the api
HttpMethod.GET, // use the Http verb "GET"
new HttpEntity<>(headers), // optional headers, e.g. for basic auth
Article[].class // the expected response type is Article[]
);
Article[] articles = response.getBody();
List<Article> list = Arrays.asList(articles); // if you need to use collections
Note, a ResponseEntity being non-null does not imply that the request was successful. You can use responseEntity.getStatusCode() to determine the status code of the response.
Be careful, however, since by default, RestTemplate throws an exception when a non-200 error code is recieved (HttpClientErrorException and HttpServerErrorException for 4XX and 5XX codes respectively). If you want your own custom error handling, you should call:
template.setErrorHandler(new ResponseErrorHandler() {
#Override
public boolean hasError(ClientHttpResponse response) throws IOException {
// implement here
}
#Override
public void handleError(ClientHttpResponse response) throws IOException {
// implement here
}
});
For persistence into MongoDB, you can use JPA, although JPA is not a perfect fit for MongoDB due to its inherently relational nature clashing with Mongo's non-relational structure. Something like Spring Data can more sensibly map this, and is worth looking into: https://spring.io/projects/spring-data-mongodb
EDIT - calling this code
Typically, I will create an class/interface with implementation (called ArticleResource for example) that looks like:
public class ArticleResource {
private final RestTemplate template = new RestTemplate();
public List<Article> getAllArticles() {
ResponseEntity<Article[]> response = template.exchange(API_URL, HttpMethod.GET, new HttpEntity<>(headers), Article[].class);
// some error checking here
return response.getBody() == null ? Collections.emptyList() : Arrays.asList(response.getBody());
}
}
For methods that expect a single value (e.g. findArticleByTitle(String title)) I typically return an Optional<Article> (it is bad practice to return Optional<List<T>>, as an empty list represents "no values" already).
From there in your code you can call:
ArticleResource resource = new ArticeResource();
// if you want to print all the names for example:
resource.getAllArticles().stream().map(Article::getName).forEach(System.out::println);

Related

Dynamic filtering of a field in the response from a RESTful webservice enpoint that returns a List of domain objects

Given a RESTful web service developed using the Spring Boot framework, I wanted a way to suppress the birthDate of all Users in the response. This is what I implemented after looking around for a solution :
#RestController
public class UserResource {
#Autowired
private UserDAOservice userDAOService;
#GetMapping("/users")
public MappingJacksonValue users() {
List<User> users = userDAOService.findAll();
SimpleBeanPropertyFilter filter = SimpleBeanPropertyFilter
.filterOutAllExcept("id", "name");
FilterProvider filters = new SimpleFilterProvider().addFilter(
"UserBirthDateFilter", filter);
MappingJacksonValue mapping = new MappingJacksonValue(users);
mapping.setFilters(filters);
return mapping;
}
}
However, when I hit the rest end point in the browser, I can still see the birth date of the user in the response :
{
"id": 1,
"name": "Adam",
"birthDate": "1980-03-31T16:56:28.926+0000"
}
Question 1 : What API can I use to achieve my objective?
Next, assuming that I want to adhere to HATEOAS in combination with filtering, how can I go about doing this. I am unable to figure out the APIs that can be used for using these two features together :
#GetMapping("/users/{id}")
public EntityModel<User> users(#PathVariable Integer id) {
User user = userDAOService.findById(id);
if (user == null) {
throw new ResourceNotFoundException("id-" + id);
}
EntityModel<User> model = new EntityModel<>(user);
WebMvcLinkBuilder linkTo = linkTo(methodOn(this.getClass()).users());
model.add(linkTo.withRel("all-users"));
//how do I combine EntityModel with filtering?
return model;
}
Question 2 : How do I combine EntityModel with MappingJacksonValue?
Note : I am aware of #JsonIgnore annotation but that would apply the filter for all end points that use the domain; however, I want to restrict the filtering only to the two endpoints above.
Turns out for this to work, I have to add the #JsonFilter annotation above the DTO and provide the same name that was used while creating the SimpleFilterProvider.
#JsonFilter("UserBirthDateFilter")
public class User {
private Integer id;
#Size(min=2, message="user name must be atleast 2 characters")
#ApiModelProperty(notes="user name must be atleast 2 characters")
private String name;
#Past
#ApiModelProperty(notes="birth date cannot be in the past")
private Date birthDate;
//other methods
}
There is an easier way to do this, on your transfer object (the class you are sending back to the client), you can simply use the #JsonIgnore annotation to make sure the field is not serialized, and therefore sent to the client. So simply add #JsonIgnore inside your User class for your birthDay field.
You can also read more here about this approach:
https://www.baeldung.com/jackson-ignore-properties-on-serialization
If you need to return a different object for different endpoints (User without birthDay in your case, only for specific) you should create separate transfer objects and use those for their respective endpoints. You can pass your original entity (User) in the constructor to those classes and copy over all fields needed.
You can use Jackson's #JsonView feature. With this, you can tell a certain request mapping to produce serialized JSON with chosen set of properties.
public class View {
interface UserDetails {}
}
public class User {
#JsonView(View.UserDetails.class)
private Long id;
#JsonView(View.UserDetails.class)
private String name;
private String birthdate;
}
Controller be like
#JsonView(View.UserDetails.class)
#GetMapping("/users")
public MappingJacksonValue users() {
....
}
For question 2, I had the exact same question as you did, and here's what I did. It seems to be working:
#GetMapping(path = "/users/{id}")
public MappingJacksonValue retrieveUser(#PathVariable int id){
User user = service.findOne(id);
if(user==null){
throw new UserNotFoundException("id-"+id);
}
//"all-users", SERVER_PATH + "/users"
EntityModel<User> resource = EntityModel.of(user);
WebMvcLinkBuilder linkTo =
linkTo(methodOn(this.getClass()).retrieveAllUsers());
resource.add(linkTo.withRel("all-users"));
SimpleBeanPropertyFilter filter = SimpleBeanPropertyFilter.filterOutAllExcept("id");
FilterProvider filters = new SimpleFilterProvider().addFilter("UserFilter",filter);
MappingJacksonValue mapping = new MappingJacksonValue(resource);
mapping.setFilters(filters);
return mapping;
}
Response for HTTP GET localhost:8080/users/1
{
"id": 1,
"links": [
{
"rel": "all-users",
"href": "http://localhost:8080/users"
}
]}

Converting a JSON with array of objects to proper Java object

I have a simple Spring Boot project in which a scheduler periodically consumes a RESTful API and converts the incoming JSON file.
The JSON file is actually an array of Objects with some Keys and Values:
[
{"CoID":1,"CoName":"کشاورزی و دامپروری مگسال","CoNameEnglish":"MagsalAgriculture & Animal Husbandry Co.","CompanySymbol":"MAGS","CoTSESymbol":"زمگسا","GroupID":1,"GroupName":"كشاورزی و دامپروری","IndustryID":1,"IndustryName":"كشاورزی، دامپروری و خدمات وابسته به آن","InstCode":"5054819322815158","TseCIsinCode":"IRO1MAGS0006","TseSIsinCode":"IRO1MAGS0001","MarketID":1,"MarketName":"بورس"},
{"CoID":2,"CoName":"ذغالسنگ نگین طبس","CoNameEnglish":"Negin Tabas Lignite Co.","CompanySymbol":"TBAS","CoTSESymbol":"کطبس","GroupID":2,"GroupName":"استخراج و انبار ذغال سنگ سخت","IndustryID":2,"IndustryName":"استخراج ذغال سنگ","InstCode":"8977369674477111","TseCIsinCode":"IRO1TBAS0004","TseSIsinCode":"IRO1TBAS0001","MarketID":1,"MarketName":"بورس"},{"CoID":3,"CoName":"معدنی و صنعتی چادرملو","CoNameEnglish":"Chadormalu Mining & Industrial Co.","CompanySymbol":"CHML","CoTSESymbol":"کچاد","GroupID":3,"GroupName":"استخراج سنگ معدن های فلزی آهنی","IndustryID":3,"IndustryName":"استخراج كانه های فلزی","InstCode":"18027801615184692","TseCIsinCode":"IRO1CHML0000","TseSIsinCode":"IRO1CHML0001","MarketID":1,"MarketName":"بورس"}
...
]
I have a class called Company with similar fields to one of objects in the array within the JSON file:
#JsonIgnoreProperties(ignoreUnknown = true)
public class Company {
private int CoID;
private String CoName;
private String CoNameEnglish;
private String CompanySymbl;
private String CoTSESymbl;
private int GroupID;
private String GroupName;
private int IndustryID;
private String IndustryName;
private String IndustryCode;
private String TseCIsinCode;
private String TseSIsinCode;
private int MarketID;
private String MarketName;
// And proper getters, setters and constructor //
I also created a wrapping class called CompanyList:
public class CompanyList {
private ArrayList<Company> companyList;
public ArrayList<Company> getCompanyList() {
return companyList;
}
public void setCompanyList(ArrayList<Company> companyList) {
this.companyList = companyList;
}
public CompanyList() {
}
#Override
public String toString() {
return "CompanyList [companyList=" + companyList + "]";
}
}
I have tried three different ways to fulfill this requirement:
First:
Object[] forNow = restTemplate.getForObject("somewhere", Object[].class);
List<Object> cp= Arrays.asList(forNow);
This one works properly.
Second:
RestTemplate restTemplate = new RestTemplate();
ResponseEntity<List<Company>> response = restTemplate.exchange(
"somewhere",
HttpMethod.GET,
null,
new ParameterizedTypeReference<List<Company>>(){});
List<Company> companies = response.getBody();
log.info(companies.toString());
This one is compiled successfully but returns null and 0 in all fields.
Third:
CompanyList cp = restTemplate.getForObject("somewhere", CompanyList.class);
log.info(cp.getCompanyList().toString());
This one raises an exception:
Error while extracting response for type [class ir.pisys.rest.CompanyList] and content type [application/json;charset=utf-8];
nested exception is org.springframework.http.converter.HttpMessageNotReadableException: JSON parse error: Cannot deserialize instance of ir.pisys.rest.CompanyList out of START_ARRAY token;
nested exception is com.fasterxml.jackson.databind.exc.MismatchedInputException: Cannot deserialize instance of ir.pisys.rest.CompanyList out of START_ARRAY token
So I have some questions here:
1- Is the first approach an optimized one? (Compared to others)
2- How can I fix the two other approaches?
The second and third approaches should work fine.
You need to check your json response structure.
You could use following jsons for tests (they work with your code):
Second approach:
[{"tseCIsinCode":null,"tseSIsinCode":null,"coName":"n1","industryID":0,"coID":0,"coNameEnglish":null,"companySymbl":null,"coTSESymbl":null,"groupID":0,"groupName":null,"industryName":null,"industryCode":null,"marketID":0,"marketName":null},{"tseCIsinCode":null,"tseSIsinCode":null,"coName":"n2","industryID":0,"coID":0,"coNameEnglish":null,"companySymbl":null,"coTSESymbl":null,"groupID":0,"groupName":null,"industryName":null,"industryCode":null,"marketID":0,"marketName":null}]
Third:
{"companyList":[{"coName":"n1","coID":0,"coNameEnglish":null,"companySymbl":null,"coTSESymbl":null,"groupID":0,"groupName":null,"industryID":0,"industryName":null,"industryCode":null,"tseCIsinCode":null,"tseSIsinCode":null,"marketID":0,"marketName":null},{"coName":"n2","coID":0,"coNameEnglish":null,"companySymbl":null,"coTSESymbl":null,"groupID":0,"groupName":null,"industryID":0,"industryName":null,"industryCode":null,"tseCIsinCode":null,"tseSIsinCode":null,"marketID":0,"marketName":null}]}
Update:
Second approach fix:
Change your json fields name - "CoName" -> "coName", "CoID" -> "coID" and so on. After that changes it will work pirfectly.
Third approach fix:
Wrap your json with "{\"companyList\":[...]
And change fields name as for second approach
Second Update
If you can't change json from response. You could use mapping in your Company class
#JsonProperty("CoName")
private String CoName;

Custom response on bad request using spring RestController

I have the following controller. I am using Spring to create Restful APIs.
#RestController
public class UserController extends RestControlValidator {
#RequestMapping(value = "/user/", method = RequestMethod.POST, headers = "Accept=application/json", consumes = "application/json", produces = MediaType.APPLICATION_JSON_VALUE)
public #ResponseBody List newUser(#RequestBody #Valid UserInput input,BindingResult result)
{Some code}
}
The UserInput class looks like this:
public class UserInput{
#NotEmpty
private String emailId;
#NotEmpty
private String fName;
private String lName;
private int sex;
//getters and setters
Now when I try and access /user/ with data {"sex":"Male"}, I get the following response:
I want the response in case of such a request to be:
{"errors":{"sex":"The value must be an integer"}}
Is there any way of customising BAD REQUEST responses in Spring?
Considering the current scenario the most ideal solution would be to alter the behavior of HandlerMethodArgumentResolve as the json to pojo constructed by #RequestBody fails because we dont get a chance to check the wrong data and this check can very well be done in the custom message converter
A. first we would need to create LanguageMessageConverter as follows
public class LanguageMessageConverter extends
AbstractHttpMessageConverter<Language> {
private Gson gson = new Gson();
public LanguageMessageConverter() {
super(new MediaType("application", "json", Charset.forName("UTF-8")));
}
#Override
protected boolean supports(Class<?> clazz) {
return Language.class.equals(clazz);
}
Map<String, String> mp = new HashMap<>();
#Override
protected Language readInternal(Class<? extends Language> clazz,
HttpInputMessage httpInputMessage) throws IOException,
HttpMessageNotReadableException {
Map langmp = gson.fromJson(
convertStreamToString(httpInputMessage.getBody()), Map.class);
for (Field field : clazz.getDeclaredFields()) {
if (!langmp.get(field.getName()).getClass().getCanonicalName().equals(field.getType().getCanonicalName())) {
if (field.getType().getCanonicalName().equals("java.lang.Integer")||field.getType().getCanonicalName().toString().equals("int")) {
langmp.put(field.getName(), "0");
} else if (field.getType().equals("java.lang.String")) {
//TODO COde needs to be improved here because this check is not efficient
langmp.put(field.getName(), "wrong");
}
}
}
Language lang = gson.fromJson(gson.toJson(langmp), clazz);
return lang;
}
we need to set the media type new MediaType("application", "json", Charset.forName("UTF-8")) which will make sure this class intervenes the mentioned MIME type
Considering we need to manipulate the result I found it best to convert it to map langmp (There are better JSON Parsers which can be used)
Since we need to to understand the existing type I used reflection api to get the fields via getDeclaredFields()
Using the above made the logical check using the datatype to understand if the type is incorrect for eg if the field datatype is int and if it is found as String then corresponding map value will be substituted
once that is done the map will hold the updated values where in if the data was wrong a default value would be set eg if the int var is set to 0 since the originating json had a String in it.
Once that is done the updated map is converted to the concerned class.
B. Secondly we need to register the custom MessageConverter in the dispatcher xml i.e. LanguageMessageConverter
<mvc:annotation-driven >
<mvc:message-converters register-defaults="true">
<bean class="com.comp.org.controller.LanguageMessageConverter" />
</mvc:message-converters>
</mvc:annotation-driven>
register-defaults="true" is very important since we are adding Custom MessageConverter but we also need the other existing converters working along with the one we have added
LanguageMessageConverter needs to be registered here.
C. Considering the concerned pojo is populated with the necessary details it would reach our controller post processing in the custom converter now we would add the manual validation eg. if the int variable has 0 the necessary error json should be returned
As per your request even if the json consists of the wrong data the custom message converter should process it and accordingly in the controller we can validate the condition mentioned.
The code definitely can be improved further. Kindly let me know if this solution fulfilled your requirement or any part of the code requires further elaboration and hopefully addressed your concern.
I had the same issue, than I solved that way:
Create an Object called Error, like that (don't forget to implement Serializable...):
private String fieldName;
private String errorCode;
private String defaultMessage;
public Error() {
}
public Error(String fieldName, String errorCode, String defaultMessage) {
this.fieldName = fieldName;
this.errorCode = errorCode;
this.defaultMessage = defaultMessage;
}
/* getters, setters */
Inside the #RestController method you ave to call inputValidator.validate() method (if you didn't create an Object Validator for your UserInput then we're really don't speaking the same language...)
// validating the userInput
userInputValidator.validate(userInput, bindingResult);
if (bindingResult.hasErrors()) {
List<Error> errors = new ArrayList<>(bindingResult.getErrorCount());
for (FieldError fieldWithError : bindingResult.getFieldErrors()) {
errors.add(new Error(fieldWithError.getField(), fieldWithError.getCode(), fieldWithError.getDefaultMessage()));
}
return errors;
}
// in case of success:
return null;
Finally you'll have to translate the JSON object to your client side. You'll have two kind of objects:
3.1. null (undefined depending on the language you're using)
3.2. A JSON object like that:
[
{
"fieldName": "name",
"errorCode": "user.input.name.in.blank",
"defaultMessage": "Insert a valid name!"
},
{
"fieldName": "firstPhone",
"errorCode": "user.input.first.phone.blank",
"defaultMessage": "Insert a valid first phone!"
}
]

Dropwizard example giving 400 error when creating new resource

I am new to the Dropwizard framework. I am trying to work on creating a new resource similar to person and people resource mentioned in the tutorial here https://github.com/dropwizard/dropwizard/tree/master/dropwizard-example.
I am creating a document class like this -
#Entity
#Table(name = "document")
#NamedQueries({
#NamedQuery(
name = "com.example.helloworld.core.Document.findAll",
query = "SELECT d FROM Document d"
),
#NamedQuery(
name = "com.example.helloworld.core.Document.findById",
query = "SELECT d FROM Document d WHERE d.Id = :Id"
)
})
public class Document {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private long Id;
#Column(name = "ProcessingSetID")
private String ProcessingSetID;
#Column(name = "processed")
private String processed;
public long getId() {
return Id;
}
public void setId(long id) {
this.Id = id;
}
public String getProcessingSetID() {
return ProcessingSetID;
}
public void setProcessingSetID(String processingSetID) {
ProcessingSetID = processingSetID;
}
public String getProcessed() {
return processed;
}
public void setProcessed(String processed) {
this.processed = processed;
}
}
My document Dao is like this,
public Optional<Document> findById(Long id) {
return Optional.fromNullable(get(id));
}
public Document create(Document document) {
return persist(document);
}
public List<Document> findAll() {
return list(namedQuery("com.example.helloworld.core.Document.findAll"));
}
}
I am trying to call the POST method on my document resource,
#Path("/documents")
#Produces(MediaType.APPLICATION_JSON)
public class DocumentsResource {
private final DocumentDao documentDAO;
private static final Logger log = LoggerFactory.getLogger(DocumentsResource.class);
public DocumentsResource(DocumentDao documentDAO) {
this.documentDAO = documentDAO;
}
#POST
#UnitOfWork
public Document createDocument(Document document) {
log.info("inside POST method of document.");
System.out.println("inside POST method of document.....");
return documentDAO.create(document);
}
#GET
#UnitOfWork
public List<Document> listDocuments() {
return documentDAO.findAll();
}
}
But I am getting a 400 response back from my client request, please find below the client request
Client client = Client.create();
WebResource webResource = client.resource("http://localhost:8080/documents");
String input = "{\"processed\":\"new process\",\"ProcessingSetID\":\"new iD\"}";
ClientResponse response =
webResource.type("application/json").post(ClientResponse.class, input);
if (response.getStatus() != 200) {
throw new RuntimeException("Failed : HTTP error code : "
+ response.getStatus());
}
I tried to debug the problem, but the call is not reaching the POST method at the first place. It seems that it is not creating the document object from the JSON string, but i could not see a reason for that. Also when I do an entry directly in my database and make a GET call, perfect JSON string equivalent to object is received.
To get helpful message regarding 400 error, register this on jersey:
environment.jersey().register(new JsonProcessingExceptionMapper(true));
It will give more detailed message on 400 response, useful for debugging.
A little background: Dropwizard utilizes Jersey, and Jersey is what ultimately gives you back the 400 Bad Request response, probably along with a vague and laconic message.
In order to see exactly what did bother Jackson (which in turn bothered Jersey), I started out by sending a blank (empty) JSON object and see whether it was accepted (it did - and all the fields in the POJO where zero-initialized). Then I started to add fields, sending each such object along, until I reached the problematic field (in my case it was a boolean field which should have been a Boolean).
I think I can spot two difficulties in your POJO (the Document class):
The getters/setters should be annotated with #JsonProperty.
Try to change Id's type to Long (nullable long). If you are concerned about getting a null in that field, you can have the getter return a zero or any default value instead.
I faced the same issue. The errors are suppressed and not passed properly in the stack trace.
What I did was to add a try catch around the function. Then added a debugger point in the exception. I was able to figure out the exact reason.
You could try something like this.
#POST
#UnitOfWork
public Document createDocument(Document document) throws Exception{
....
}
Add debugger points in the Exception class. You will find out the exact reason of the parsing failure.
Hope I am clear and it helps!
Http status 400 means "bad request". Which it is, the json you are sending is not a valid Document.
This in turn means you will never reach the body of
#POST
#UnitOfWork
public Document createDocument(Document document){}
To solve it, try passing the json:
String input = "{\"id\":\"123456789\",\"processed\":\"new process\",\"ProcessingSetID\":\"new iD\"}";
Replace 123456789 with your actual id.
PS. it might be a good idea (depending on your scenario) to create a DTO for Document instead of passing the actual entity around.
If you are registering the Jersey's CsrfProtectionFilter in your Dropwizard *Application.java within the run(...) method, make sure you're adding the X-Requested-By header to all of your state changing HTTP calls (POST, PUT, etc). The server will return an HTTP 400 Bad Request if that header is not found in the request.

how to easily convert a JSON to a string for logging purposes

I will try to explain what I'm trying to accomplish as clear as I can.
I'm writing the back end of a web application, that uses REST APIs for extracting data that is used for reports in the client side.
The framework I'm writing on uses Codehaus jackson for parsing the requests from JSON to data objects (data beans).
I have a bunch of APIs of this sort, 10-15.
each of them gets a different request object from the client side (though some inheritance do exist).
what I want to do is add logging (using log4j) for each of these APIs so that when I enter each of the methods the request data object will be logged.
the simple solution would be to implement a toString() method for each of these data objects, but I want to avoid going over all of these data objects and see if there's a solution similiar to the way that jackson parses the JSON into an object.
I.e have the object converted back to its textual format in order to put it into the log.
I assume there's so easy way to do so.
This is an example of a REST API and its data bean:
#POST
#Path("/path123/")
#Produces(MediaType.APPLICATION_JSON)
#Consumes(MediaType.APPLICATION_JSON)
public Response getSomeData(#Context HttpServletRequest httpServletRequest, DataBeanExample bean){
DataBeanExample resultBean;
//DO SOME STUFF , for example take the bean, extract parameters from it and call some other api.
return Response.ok(resultBean, MediaType.APPLICATION_JSON).build();
}
#XmlAccessorType(XmlAccessType.FIELD)
#XmlRootElement(name = "DataBeanExample")
public class DataBeanExample{
#XmlElement(name = "timeFrame", required = true)
private String timeFrame = "";
#XmlElement(name = "timeFrom",required = true)
private long timeFrom;
#XmlElement(name = "timeTo",required = true)
private long timeTo;
public String getTimeFrame() {
return timeFrame;
}
public void setTimeFrame(String timeFrame) {
this.timeFrame = timeFrame;
}
public long getTimeTo() {
return timeTo;
}
public void setTimeTo(long timeTo) {
this.timeTo = timeTo;
}
public long getTimeFrom() {
return timeFrom;
}
public void setTimeFrom(long timeFrom) {
this.timeFrom = timeFrom;
}
}
In the example, what I want to do is at the beginning of "getSomeData" take the object bean and have it logged.
Probably this might work
new ObjectMapper().writeValue(System.out, dataBeanExampleInstance)
or writeValueAsString
Do you know about:
JSON.stringify

Categories

Resources