Spring boot JSON response - json

Here's my code
#RequestMapping("/bookList")
public List<Books> list() {
return bookService.booksList();
}
public class Books {
private String author;
private String isbn;
private String title;
}
Current response
[["TOM",123456,"ABC"],["JANE",789000,"CDE"]]
Expected response
"Books": [
{"author": "TOM", "isbn": "123456", "title": "ABC"},
{"author": "JANE", "isbn": "789000", "title": "CDE"}
]
What is the code change I need to make?

Your List<Books> is correctly returned as JSON. Your option would be to wrap it into another object:
public class BookList {
public List<Books> books;
}
and return a BookListinstead of List<Books>.
But to be honest, I would not recommend you do do that. It's not very restful.

session.createQuery returns Object[]. I used Criteria query with projections inside my DAOIMPL class and I got the expected output.

Related

Serialize Java List to JSON without field name

public class MyResponse {
private List<Data> data;
public static class Data {
private long id;
private String name;
}
}
Using Jackson this gets serialized to the following JSON:
{
"data": [
{
"id": 115125,
"name": "AAAY"
}
]
}
What I need instead is the JSON like this, i,e. omitting the wrapping Data class:
[
{
"id": 115125,
"name": "AAAY"
}
]
Place the #JsonValue annotation on the data field:
public class MyResponse {
#JsonValue
private List<Data> data;
...
}

how to represent JSON as treeview in Javafx

I have a Film model like below:
public class Film{
private String name;
private String category;
private Actor[] actors;
private MarketingPlan marketingPlan;
}
class Actor{
private String name;
private double salary;
}
class MarketingPlan{
private String nameOfPlan;
private Country[] affectedCountries;
}
class Country{
private int countryID;
private String marketingText;
}
which generate a JSON like this:
{
"name": "My First Film",
"category": "action",
"marketingPlan": {
"name": "plan1",
"affectedCountries": [
{
"marketingText": "This is a marketing text",
"countryID": 332
}
]
},
"actors": [
{
"name": "John",
"salary": 123456
}
]
}
I would like to represent my JSON result above as tree structure in JavaFX. Can anyone give me some hint or suggest me some tutorial how can I do it. Thank you very much in advanced!

How automatically parse response String into Map using RestTemplate

I'm using RestTemplate to retrieve list of issues from Jira. As response I get String with lots of fields, some of them are arrays. Request looks like:
ResponseEntity<String> response = restTemplate.exchange(url, HttpMethod.GET, entity, String.class);
Response string looks like:
{
"expand": "schema,names",
"total": 12,
"issues": [
{
"id": "32",
"key": "TEST-1",
"fields": {
"fixVersions": [
{
"description": "",
"releaseDate": "2017-04-02"
}
]
},
{
"id": "32",
"key": "TEST-2",
"fields": {
"fixVersions": [
{
"description": "",
"releaseDate": "2017-04-01"
}
]
}
]
}
Is it possible to convert this String into Map, where Object could be String or List of Map or something like this, without defining appropriate objects. As result, I'd like to have possibility to access description by: response.getIssues().get(0).getFields().getFixVersion().get(0).getDescription()
In such occasion, defining chain of specific objects looks too cumbersome.
You can create your own POJO classes which corresponds to the structure of the response JSON.
Based on the json that you have shared, you can have a class structure like this :
public class Response {
private String expand;
private String total;
private List<Issues> issues;
}
public class Issues {
private String id;
private String key;
private Map<String, List<FixVersions> fields;
}
public class FixVersions {
private String description;
private String releaseData;
}
Your GET call will change to the following :
ResponseEntity response = restTemplate.exchange(url,
HttpMethod.GET, entity, Response.class);
P.S. - All the fields in the POJO class must have their getters and
setters as well.

What is the convenient way to deserialize JSON(links + embedded container) using spring-hateoas?

colleagues!
We want to write Rest Client to service which follow the HATEOAS principle. So we have the following HAL+JSON representation and we want to deserialize it using spring-hateoas :
{
"id": "1",
"title": "album title",
"artistId": "1",
"stockLevel": 2,
"_links": {
"self": {"href": "http://localhost:8080/rest/albums/1"},
"artist": {"href": "http://localhost:8080/rest/artist/1"}
},
"_embedded": {
"albums": [{ //can be array or object
"id": "1",
"title": "album title",
"artistId": "1",
"stockLevel": 2,
"_links": {
"self": {"href": "http://localhost:8080/rest/albums/1"}
}
}],
"artist": { //can be array or object
"id": "1",
"name": "artist name",
"_links": {
"self": {"href": "http://localhost:8080/rest/artist/1"}
}
} //....
}
}
We expected the java object like this:
HalResource {
Resource<Album> //entity
List<Link> // _links
List<Resource<BaseEntity>>{ //_embedded
Resource<Album>
Resource<Artist>
....
}
}
So we have custom resource representation with embedded(list of resources) and entity(single resource):
#XmlRootElement(name = "resource")
public class HalResource<EntityType, EmbeddedType> extends Resources<EmbeddedType> {
#JsonUnwrapped
private EntityType entity;
public HalResource() {
}
public HalResource(Iterable<EmbeddedType> content, Link... links) {
super(content, links);
}
public EntityType getEntity() {
return entity;
}
public void setEntity(EntityType entity) {
this.entity = entity;
}
}
DTO classes:
public abstract class BaseEntity{}
#XmlRootElement(name = "album")
public class Album extends BaseEntity {
private String id;
private String title;
private String artistId;
private int stockLevel;
// getters and setters...
}
#XmlRootElement(name = "artist")
public class Artist extends BaseEntity {
private String id;
private String name;
// getters and setters...
}
And we want to get something like this, where Entity will be Artist or Album, but HalResourcesDeserializer return Resource.class with null content.
HalResource<Album, Resource<Entity>> resources =
restClient.getRootTarget().path("albums/1").queryParam("embedded", true).request().accept("application/hal+json")
.get(new GenericType<HalResource<Album, Resource<Entity>>>() {});
By using #JsonTypeInfo and #JsonSubTypes anotations we successfully deserialized our JSON(you can see the example on the github), but we don't want to have some additional type filds and anotattions in our DTO and JSON format.
We see one solution that is create a custom deserializer which can processing that.
So the question is: What is the convenient way to deserialize our JSON(links + embedded container) using spring-hateoas?
We use spring-hateoas 0.16v(but we tried 0.19v) and glassfish jersey 2.22.1
Thank you!

How to use json parese this content

I got the json string like this,
{
"resultCode": 200,
"operation": 0,
"resultMsg": "正常初始化",
"debugMsg": "",
"resultCount": 3,
"result": {
"operation": 0,
"verify_key": "6f3e9169e4fcfbe4a52606c013348650",
"user_id": 41201
}
}
But I want to convert it to,
public class ClientResult {
String result;
String resultMsg;
String debugMsg;
int resultCode;
int operation;
}
.If i use gson.fromJson(result, ClientResult.class),get a exception
com.google.gson.JsonSyntaxException: java.lang.IllegalStateException: Expected a string but was BEGIN_OBJECT at line 1 column 118
I just want to parse it to String, not Object, because the result field of ClientResut is not same,it maybe a array sometimes.
the result sometimes like
{
"resultCode": 200,
"operation": 0,
"resultMsg": "",
"debugMsg": "",
"resultCount": 12,
"result": {
"id": "4392",
"pm25": "44",
"time": "1433403001",
"l_temperature": "9",
"h_temperature": "20",
"c_temperature": "14",
"weather_icon": "http://60.31.215.212/zsgj/Public/weather/zhenyu.png",
"tm_l_temperature": "8",
"tm_h_temperature": "25",
}
}
So i just want to parse it to a String..
Its because you are doing it wrong, "result" is another json object in your json, You can go with an approach of creating 2 POJOs for your Json which you can use in your GSON.
public class Result
{
private String operation;
private String verify_key;
private String user_id;
}
and your original class
public class ClientResult
{
private String resultMsg;
private Result result;
private String debugMsg;
private String operation;
private String resultCount;
private String resultCode;
}