Moshi toJSON sorts alphabetically? - moshi

Can anyone tell why moshi toJSON giving alphabetical sorted JSON string
Model Class :
Class { String firstName; String emailID;}
Resulting JSON:
{ "emailID" : someMail, "firstName" : name }

Related

Ignore inner object if all the properties are null during ObjectMapper deserialization

I have a below Product class
#JsonInclude(JsonInclude.Include.NON_EMPTY)
public class Product {
private String id;
private String status;
private Price price
}
#JsonInclude(JsonInclude.Include.NON_NULL)
public class Price {
private String originalPrice;
private String newPrice;
}
After deserialization I'm getting the output json as below
{
"id" : 2113,
"status" : "New",
"price" : { },
}
But I'm expecting the output as below without price details as price has all the attributes as null
{
"id" : 2113,
"status" : "New"
}
I tried #JsonInclude(JsonInclude.Include.NON_EMPTY) at class level but its not working.
Any help is much appreciated.
This may be because your Price object is not null. Somewhere Price is initialized and included empty.
See example here
If this is not the case then, you can add code for your service/controller which returns Product.

How to query nested objects from MongoDB using Spring Boot (REST) and TextQuery?

I am writing RESTful API to search MongoDB collection named 'global' by criteria using TextQuery. My problem is that I cannot access nested object fields when doing query.
For example this works:
GET localhost:8080/search?criteria=name:'name'
And this does not:
GET localhost:8080/search?criteria=other.othername:'Other Name'
I have MongoDB json structure (imported from JSON into 'global' collection as whole nested objects)
[{
"name": "Name",
"desc": "Desc",
"other" {
"othername": "Other Name",
}
},
{
"name": "Name",
"desc": "Desc",
"other" {
"othername": "Other Name",
}
}
]
And classes (with getters & setters & etc):
#Document(collection="global")
public class Global{
#TextIndexed
String name;
#TextIndexed
String desc;
Other other;
...
}
public class Other{
String othername;
...
}
My controller has method
#GetMapping("/search")
public Iterable<Global> getByCriteria(#RequestParam("criteria") String criteria) {
...
}
And I am trying to write text search with
public Iterable<Global> findByCriteria(String criteria) {
TextCriteria criteria = TextCriteria.forDefaultLanguage().matching(criteria);
TextQuery query = TextQuery.queryText(criteria);
return mongoTemplate.find(query, Global.class);
}
You need to add #TextIndexed to your other field.
public class Global{
#TextIndexed
String name;
#TextIndexed
String desc;
#TextIndexed
Other other;
...
}
Note: All nested object fields are searchable
or you may add #TextIndexed for each nested object field:
public class Other {
#TextIndexed
String othername;
...
}

Deserializing interfaces with Spring Data MongoDB

i've currently a problem with the serialize/deserialize in MongoDB of an object that contains an attribute defined by a marker interface. The implementations are Enum.
My versions are Spring 4.3.7 and Spring-data-mongodb 1.10.1.
My code sounds like:
public interface EventType {
String getName();
}
public interface DomainEvent extends Serializable {
UUID getId();
LocalDateTime getOccurredOn();
EventType getEventType();
String getEventName();
}
public abstract class AbstractDomainEvent implements DomainEvent {
private UUID id;
private LocalDateTime occurredOn;
private EventType eventType;
protected AbstractDomainEvent(EventType eventType) {
this.id = UUID.randomUUID();
this.occurredOn = LocalDateTime.now();
this.eventType = eventType;
}
}
public class MyEventOne extends AbstractDomainEvent {
private Object myConcreteData;
public MyEventOne(Object data) {
super(MyEventType.EVENT_ONE);
this.myConcreteData = data;
}
}
public enum MyEventType implements EventType {
EVENT_ONE,
EVENT_N;
#Override
public String getName() {
return this.name();
}
}
Ok, well.
My problem is when I try to deserialize an event persisted in mongoDB.
When I persist MyEventOne, Spring data mongo persist the object as:
{
"_class" : "xxx.xxx.xxx.MyEventOne",
"_id" : LUUID("d74478e7-258c-52c4-4fc5-aba20a30d4b6"),
"occurredOn" : ISODate("2018-02-21T14:39:53.549Z"),
"eventType" : "EVENT_ONE"
}
}
Note the eventType is a String.
When I try to read this document, I have this exception:
org.springframework.core.convert.ConverterNotFoundException: No converter found capable of converting from type [java.lang.String] to type [xxx.xxx.xxx.EventType]
Any idea? there a some solution like a insert metadata information about the concrete Enum instance, like a "_class" field?
I try insert #JsonTypeInfo annotation in EventType attribute at AbstractDomainEvent but it doesnt works.
Thank you!!!

Spring data elasticSearch returns null with findOne

I'm testing Spring data with elasticSearch. The ES server is running on a remote server in tha same room.
I have one index created a day, under an alias. I'm trying to find a simple tweet. But when I try a findOne(), it doesn't seem to work because it returns always null.
Also, findAll(ids) doesn't work because I'm using the alias, but I can't find in the documentation how to handle this.
What do I want to achieve ?
For the moment, simply retrieve a tweet with a given id_str.
The count method works, the findOne doesn't
Here are my questions
What should I do to make findOne() to work ?
Which way should I use to search on multiple indexes in this alias ?
Here is how the datas looks like in ES
{
"id_str" : "135131315100051",
"..." : "...",
"user" : {
"id_str" : "15843643228"
"..." : "..."
}
}
My model
import org.springframework.data.annotation.Id;
import org.springframework.data.elasticsearch.annotations.Document;
import org.springframework.data.elasticsearch.annotations.Field;
import org.springframework.data.elasticsearch.annotations.FieldType;
#Document(indexName = "alias", type = "tweets")
public class Tweet
{
#Id
#Field(type = FieldType.String)
private String idStr;
public String getIdStr()
{
return idStr;
}
public void setIdStr(final String idStr)
{
this.idStr = idStr;
}
#Override
public String toString()
{
return "{ id_str : " + idStr + " }";
}
}
Alias is alias, and indexes are alias_dd-mm-yyyy
My repository
import org.springframework.data.elasticsearch.repository.ElasticsearchRepository;
import com.thales.communications.osintlab.bigdata.webservices.models.Tweet;
public interface EsTweetRepository extends ElasticsearchRepository<Tweet, String>
{
Tweet findByIdStr(String idStr);
}
My test
#Test
public void shouldReturnATweet()
{
//lets try to search same record in elasticsearch
final Tweet tweet1 = tweetRepository.findOne("593768150975512576");
//final Tweet tweet = tweetRepository.findByIdStr("593897683661824000");
System.out.println("Count is " + tweet1);
//System.out.println("Count is " + tweetRepository.count());
// System.out.println(tweet.toString());
}
Of course, the tweet with the tested Id exists :). And the count() is working fine.
Thanks for your help
EDIT
Here is a sample application of what I have : https://github.com/ogdabou/es-stackoverflow-sample
It seems that spring-data-elasticsearch is look for the field "_id" and not the field "id_str". Maybe because of method parsing (look there). I'm looking for a way to bind my json "id_str" attribute to my idStr java model.
What was the real issue
We set the _id field of our tweet in Elasticsearch with the id field given by twitter. But it saves it in another format ( eg 132 becomes 1.32E2)
When I'm going a findOne() it is searching for a match with the Elasticsearch _id field and not the id_str I needed.
Solution
There, you have 2 commits, the first is the issue, the second the solution.
New repository
public interface EsTweetRepository extends ElasticsearchRepository<Tweet, String>
{
#Query("{\"bool\" : {\"must\" : {\"term\" : {\"id_str\" : \"?0\"}}}}")
Tweet findByIdStr(String idStr);
}
The model
#Document(indexName = "my_index_01", type = "tweets")
public class Tweet
{
// Elasticsearch object internal id. Look at field "_id"
#Id
private String id;
// Twitter internal id, saved under the "id_str" field
#Field(type = FieldType.String)
private String id_str;
#Field(type = FieldType.String)
private String text;
public String getId_str()
{
return id_str;
}
public void setId_str(final String id_str)
{
this.id_str = id_str;
}
public String getText()
{
return text;
}
public void setText(final String text)
{
this.text = text;
}
public String getId()
{
return id;
}
public void setId(final String id)
{
this.id = id;
}
#Override
public String toString()
{
return "{ _id : " + id + ", id_str : " + id_str + ", text : " + text + " }";
}
}

Spring: one JPA model, many JSON respresentations

I'm writing a RESTful web service using Spring/JPA. There's a JPA model which is exposed through the web service. The 'Course' model is quite spacious - it actually is composed of several sets of data: general information, pricing details and some caches.
The issue I encounter is the inability to issue different JSON representations using the same JPA model.
The in first case I only need to return general_info set of data for courses:
GET /api/courses/general_info
in the second case I would like to return pricing set of data only:
GET /api/courses/pricing
I see the following ways to solve this, not in particular order:
To create CourseGeneralInfo and CoursePricing JPA models using
the origin database table as a source. CourseGeneralInfo model
would have its own set of fields and CoursePricing would have its
own ones. This way I would have the JSON I need.
To refactor the stuff out of the Course model/table to have
GeneralInfo and PricingDetails to be separate JPA entities. Ok, this sounds like the best one (imo) though the database is legacy and it is not something I can change easily...
Leverage some sort of DTO and Spring Mappers to convert the JPA model to representation needed in any particular case.
What approach would you recommend?
I was just reading about some really nifty features in Spring 4.1, which allow you to use different views via annotations.
from: https://spring.io/blog/2014/12/02/latest-jackson-integration-improvements-in-spring
public class View {
interface Summary {}
}
public class User {
#JsonView(View.Summary.class)
private Long id;
#JsonView(View.Summary.class)
private String firstname;
#JsonView(View.Summary.class)
private String lastname;
private String email;
private String address;
private String postalCode;
private String city;
private String country;
}
public class Message {
#JsonView(View.Summary.class)
private Long id;
#JsonView(View.Summary.class)
private LocalDate created;
#JsonView(View.Summary.class)
private String title;
#JsonView(View.Summary.class)
private User author;
private List<User> recipients;
private String body;
}
Thanks to Spring MVC #JsonView support, it is possible to choose, on a per handler method basis, which field should be serialized:
#RestController
public class MessageController {
#Autowired
private MessageService messageService;
#JsonView(View.Summary.class)
#RequestMapping("/")
public List<Message> getAllMessages() {
return messageService.getAll();
}
#RequestMapping("/{id}")
public Message getMessage(#PathVariable Long id) {
return messageService.get(id);
}
}
In this example, if all messages are retrieved, only the most important fields are serialized thanks to the getAllMessages() method annotated with #JsonView(View.Summary.class):
[ {
"id" : 1,
"created" : "2014-11-14",
"title" : "Info",
"author" : {
"id" : 1,
"firstname" : "Brian",
"lastname" : "Clozel"
}
}, {
"id" : 2,
"created" : "2014-11-14",
"title" : "Warning",
"author" : {
"id" : 2,
"firstname" : "Stéphane",
"lastname" : "Nicoll"
}
}, {
"id" : 3,
"created" : "2014-11-14",
"title" : "Alert",
"author" : {
"id" : 3,
"firstname" : "Rossen",
"lastname" : "Stoyanchev"
}
} ]
In Spring MVC default configuration, MapperFeature.DEFAULT_VIEW_INCLUSION is set to false. That means that when enabling a JSON View, non annotated fields or properties like body or recipients are not serialized.
When a specific Message is retrieved using the getMessage() handler method (no JSON View specified), all fields are serialized as expected:
{
"id" : 1,
"created" : "2014-11-14",
"title" : "Info",
"body" : "This is an information message",
"author" : {
"id" : 1,
"firstname" : "Brian",
"lastname" : "Clozel",
"email" : "bclozel#pivotal.io",
"address" : "1 Jaures street",
"postalCode" : "69003",
"city" : "Lyon",
"country" : "France"
},
"recipients" : [ {
"id" : 2,
"firstname" : "Stéphane",
"lastname" : "Nicoll",
"email" : "snicoll#pivotal.io",
"address" : "42 Obama street",
"postalCode" : "1000",
"city" : "Brussel",
"country" : "Belgium"
}, {
"id" : 3,
"firstname" : "Rossen",
"lastname" : "Stoyanchev",
"email" : "rstoyanchev#pivotal.io",
"address" : "3 Warren street",
"postalCode" : "10011",
"city" : "New York",
"country" : "USA"
} ]
}
Only one class or interface can be specified with the #JsonView annotation, but you can use inheritance to represent JSON View hierarchies (if a field is part of a JSON View, it will be also part of parent view). For example, this handler method will serialize fields annotated with #JsonView(View.Summary.class) and #JsonView(View.SummaryWithRecipients.class):
public class View {
interface Summary {}
interface SummaryWithRecipients extends Summary {}
}
public class Message {
#JsonView(View.Summary.class)
private Long id;
#JsonView(View.Summary.class)
private LocalDate created;
#JsonView(View.Summary.class)
private String title;
#JsonView(View.Summary.class)
private User author;
#JsonView(View.SummaryWithRecipients.class)
private List<User> recipients;
private String body;
}
#RestController
public class MessageController {
#Autowired
private MessageService messageService;
#JsonView(View.SummaryWithRecipients.class)
#RequestMapping("/with-recipients")
public List<Message> getAllMessagesWithRecipients() {
return messageService.getAll();
}
}
In Spring Data REST 2.1 there is a new mechanism for this purpose - Projections (It's now part of spring-data-commons).
You'll need to define interface, containing exactly exposed fields:
#Projection(name = "summary", types = Course.class)
interface CourseGeneralInfo {
GeneralInfo getInfo();
}
After that Spring will be able to find it automagically in your source, and you could make requests to your existing endpoints, like this:
GET /api/courses?projection=general_info
Based on
https://spring.io/blog/2014/05/21/what-s-new-in-spring-data-dijkstra
Spring sample project with projections:
https://github.com/spring-projects/spring-data-examples/tree/master/rest/projections

Resources