monitorjbl / json-view Goto Github PK
View Code? Open in Web Editor NEWProgrammatic JSON views with Jackson
License: GNU General Public License v3.0
Programmatic JSON views with Jackson
License: GNU General Public License v3.0
When using bidirectional mapping between a parent and a child class (in my class using hibernate), we use @JsonBackReference to prevent infinite iterations. This does not work with this serializer.
It looks like JsonViewSerializer is sometimes using the path for class matching, which causes the match to fail.
I cam here after seeing your post in stackoverflow, which impressed and solving my problem.
I am new to spring boot and its implementation
Coming to problem : I have to model classes songs , movies
where movie id belong to song class and I joined this table with movies
In the controller how to implement to exclude all the fields of the movie except id and name .
My controller class is
@RestController
@RequestMapping("api")
public class SongsController {
@Autowired
SongsRepository songsRepository;
@RequestMapping(value = "/Songs", method = RequestMethod.GET)
public ResponseEntity<List<Songs>> getSongsList(){
return new ResponseEntity<>(songsRepository.findAll(), HttpStatus.OK);}
songs class has (id , movieid, songtitile.....)
movie class has (movieid, moviename, ..........................)
I observed that right now @JsonProperty annotation is ignored on the field.
Can you please add support or let me know if I am missing anything.
Hi,
I have problems using this library as I'm getting message:
Description:
Field adapter in com.monitorjbl.json.JsonViewSupportFactoryBean required a single bean, but 2 were found:
- requestMappingHandlerAdapter: defined by method 'requestMappingHandlerAdapter' in class path resource [org/springframework/boot/autoconfigure/web/WebMvcAutoConfiguration$EnableWebMvcConfiguration.class]
- repositoryExporterHandlerAdapter: defined by method 'repositoryExporterHandlerAdapter' in class path resource [org/springframework/data/rest/webmvc/config/RepositoryRestMvcConfiguration.class]
What should I do in order to fix this?
Thanks
Looking at your Spring MVC integration, you have the programmatic selection for serialization of the POJO object but does your library support the deserialization? For example I want to use JsonViews to control the fields that are serialized and deserialized based on the user's role.
Having to add a new method call for each thing to be included/excluded is more verbose than it needs to be. I'd prefer to be able to do this instead:
return JsonView.with(service.get(principal, id))
.onClass(TestObjectA.class, match()
.exclude("*")
.include("id", "name"))
.returnValue();
Custom Serialize for Date Object Class is not working.
POJO Class :
public class Client {
@Id
@GeneratedValue(strategy=GenerationType.SEQUENCE,generator="Client")
private Integer client_id;
@JsonSerialize(using=JacksonDateTimeSerializer.class)
public Date getCreation_date() {
return creation_date;
}
}
JacksonDateTimeSerializer Class
@Component
public class JacksonDateTimeSerializer extends StdSerializer<Date>{
/**
*
*/
private static final long serialVersionUID = 1L;
private SimpleDateFormat formatter = new SimpleDateFormat("dd-MM-yyyy HH:mm:ss");
public JacksonDateTimeSerializer() {
this(null);
}
@SuppressWarnings({ "rawtypes", "unchecked" })
public JacksonDateTimeSerializer(Class t) {
super(t);
}
@Override
public void serialize (Date value, JsonGenerator gen, SerializerProvider arg2)
throws IOException, JsonProcessingException {
System.out.println("Am Executing");
gen.writeString(formatter.format(value));
}
}
@Bean(name="ObjectMapper")
public ObjectMapper objectMapper()
{
return new ObjectMapper();
}
@Bean(name="jsonViewObjectMapper")
public ObjectMapper jsonViewObjectMapper()
{
ObjectMapper mapper = new ObjectMapper();
SimpleModule module = new SimpleModule();
module.addSerializer(JsonView.class, new JsonViewSerializer());
mapper.registerModule(module);
return mapper;
}
Using ObjectMapper instance I can able to Serialize Date using JacksonDateTimeSerializer class.
But using jsonViewObjectMapper instance i can't Serialize using JacksonDateTimeSerializer class.
How to use custom Serialize class for Date object ?
Thank you for an excellent utility. I'm using it in a JavaScript-centric Spring/Hibernate environment and I can't praise it enough.
One area that could be improved is in the handling of iterables and arrays. It renders them without issue, but there's not enough granularity when it comes to choosing or avoiding the object fields in these lists. This is because json-view doesn't prefix the fields with the list type.
For example, if I include "id", I will get all the "id" fields of all the objects in all the lists. There's no way to get the "id" from some lists and not others. Sure you could exclude lists by name and/or wildcard. But what if you need other fields so that exclusion is not possible? What if you want "id" from one list and "name" from another, yet both lists have objects with these fields?
My fix was to alter your writeList() method and determine the list type from the first object in the list (if one exists). I use that object's simple class name (uncapitalized) as the prefix. Thus List<Person> would have a "person" prefix, and you would target a person's id by using "person.id". Essentially, there would never be a situation where you wouldn't have a prefix; a field would always be associated with some object, even in a list.
Ultimately, the best solution might be to have fully qualified paths not limited to "object.field". For example, "house.family.pet.type.name"--similar to what you would expect with JSON itself.
Hi,
This dynamic Json View looks great. I have a new request -- would it be possible to exclude some specific fields in the private List<MyBigObject> contains;
? Just like the Class Matchers example, but with a little change as below:
String json = mapper.writeValueAsString(JsonView.with(list).onClass(MyObject.class, match()
.exclude("contains.id")));
A further question would be that can I exclude the 1st element in the 'contains' list? Say .exclude("contains[0]");
?
Thanks.
Hi.
I am using Version 0.15 and this scenario happens:
I have defined a getter in this way:
@JsonGetter
public String getTest(){
return "test";
}
There is no property named "test" (it is a calculated value), but there is a getter with the annotation.
The serialization is not including a property named "test" in the serializated object if there is no property named "test".
Thank you in advance.
Hi,
It is common that sometimes output json format requires different field names from POJO fields. So I think it would be nice if developers could rename field name(s) when serializing POJO to json.
Thanks for your great work!
Hello thank you for this library.
I use it that way :
But... it does not support List attributes at the moment right ?
I also have an attribute :
CustomObject o; in my class but when I say .include(a) it is just writing "a":{} in my json output.
Is it something you plan to dev on in future ?
We have a use case where in the object needs to be encrypted/decrypted before sending over the wire.
If we use this package, we get JsonView as top level Object with actual object sitting inside.
Can you provide a getter/setter for JsonView's object so that we can do this encryption/decryption stuff and send it over?
Maybe I am missing something, but it appears that any elements that I've marked as JsonUnwrapped are actually wrapped in the resulting json. If I don't use JsonView, everything is as expected.
For example:
class User {
@JsonUnwrapped
private Name name;
...
}
class Name {
private String firstName = "John";
private String lastName = "Doe";
...
}
I would expect the resulting json to come back as:
{
firstName: "John",
lastName: "Doe"
}
But it is coming back as:
{
name: {
firstName: "John",
lastName: "Doe"
}
}
Maybe I am just missing something? I also tried annotating the getter instead; to no avail.
Thank you very much for this utility!
Quick question, is there a way to use this with ResponseEntity in Spring. If so, how?
I would first like to say that what you've done here is brilliant; it was exactly what I was looking for.
However, when I define the @Bean
as you suggest in the README, my LocalDateTime
fields are no longer correctly serialized. I use jackson-datatype-jsr310
in order to serialize these fields in the correct way, but when I write:
@Bean
public JsonViewSupportFactoryBean views() {
return new JsonViewSupportFactoryBean();
}
this no longer works and I get a very weird JSON blob from the serialization.
My gradle dependencies are the following:
dependencies {
compile("com.h2database:h2")
compile("org.springframework.boot:spring-boot-starter-data-jpa")
compile("org.springframework.boot:spring-boot-starter-web")
compile("org.springframework.boot:spring-boot-devtools")
compile("org.springframework.boot:spring-boot-starter-security")
compile('org.springframework.security.oauth:spring-security-oauth2')
compile('org.springframework.security:spring-security-jwt')
compile('org.springframework.hateoas:spring-hateoas')
testCompile('org.springframework.boot:spring-boot-starter-test')
compile('com.google.api-client:google-api-client:1.20.0')
compile('com.google.apis:google-api-services-gmail:v1-rev67-1.22.0')
compile("org.springframework.boot:spring-boot-starter-mail")
compile('com.fasterxml.jackson.datatype:jackson-datatype-jsr310:2.8.9')
compile('org.hibernate:hibernate-core:5.2.10.Final')
compile('com.monitorjbl:spring-json-view:0.14') {
exclude group: "org.slf4j", module: "slf4j-log4j12"
}
}
Do you have any ideas why this is happening?
It would be helpful to make a default view for certain classes in a Spring environment. This way, common classes can be configured once instead of on each Controller.
They should use the builtin name()
method
Hi,
sorry for the issue, but i saw no way to contact you directly.
i have a controller-method, that returns a single user of the system. I have tried to hide the company of the user if the caller is no superadmin.
JsonView.with(user).onClass(User.class, match().exclude("company"))
I registered your JsonView to my CustomObjectMapper as well, but the code above throws recursively exceptions.
In the README you are always using lists. Is your library not possible on single objects?
Second question:
How do you return a ResponseBody with a void function? Is this the problem in my case? I return the user after i tried to filter the company attribute.
Thanks,
Tobias
Hi, at the moment the library is not supporting Java 8 date/time types like LocalDateTime?
I saw in the source code that has no writer for LocalDateTime type, eg.
Is there a way to extend some class or other way to make it work for Java 8 types?
I am using jackson-datatype-jsr310 in Spring Boot with serializer and deserializer and works fine. But when I use code like that
json.use(JsonView.with(obj).onClass(Obj.class, match().exclude("foo"))).returnValue()
it's not respecting the serializer of the annotation. I have this code:
@JsonSerialize(using = CustomLocalDateTimeSerializer.class)
private LocalDateTime someDate;
CustomLocalDateTimeSerializer serialize to milliseconds, but the code of CustomLocalDateTimeSerializer it's not invoked when I use the library.
The result in JSON for LocalDateTime is
someDate":{
"date":{
"year":2016,
"month":7,
"day":22
},
"time":{
"hour":20,
"minute":16,
"second":27,
"nano":881000000
}
}
Thanks, and great library...
Itanor
It is sometimes useful to transform a field during serialization. This can be used to convert the value of a field to a different language or format without relying on annotations. JsonView should expose that as an additional Match
method that can be used like so:
JsonView.with(ref)
.onClass(TestObject.class, match()
.exclude("*")
.include("str1")
.transform("str1", (TestObject t, String f) -> f.toUpperCase()))
This is a great library ,I am using this library for a while now (since 0.12-SNAPSHOT) , and it is working like a charm. (At present i am using 0.16-SNAPSHOT)
Recently I am facing a problem with my one of the Use cases, let me place my code first
# User class
public class User {
private String name;
private String emailId;
private String mobileNo;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getEmailId() {
return emailId;
}
public void setEmailId(String emailId) {
this.emailId = emailId;
}
public String getMobileNo() {
return mobileNo;
}
public void setMobileNo(String mobileNo) {
this.mobileNo = mobileNo;
}
}
# ScreenInfoPojo class
public class ScreenInfoPojo {
private Long id;
private String name;
private ScreenInfoPojo parentScreen;
private User createdBy;
private User lastUpdatedBy;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public ScreenInfoPojo getParentScreen() {
return parentScreen;
}
public void setParentScreen(ScreenInfoPojo parentScreen) {
this.parentScreen = parentScreen;
}
public User getCreatedBy() {
return createdBy;
}
public void setCreatedBy(User createdBy) {
this.createdBy = createdBy;
}
public User getLastUpdatedBy() {
return lastUpdatedBy;
}
public void setLastUpdatedBy(User lastUpdatedBy) {
this.lastUpdatedBy = lastUpdatedBy;
}
# Run code
public class TestMain {
public static void main(String[] args) throws JsonProcessingException {
User user=new User();
user.setName("ABC");
user.setEmailId("[email protected]");
user.setMobileNo("123456789");
ScreenInfoPojo screen1=new ScreenInfoPojo();
screen1.setId(1l);
screen1.setName("Screen1");
screen1.setCreatedBy(user);
screen1.setLastUpdatedBy(user);
ScreenInfoPojo screen2=new ScreenInfoPojo();
screen2.setId(2l);
screen2.setName("Screen2");
screen2.setParentScreen(Screen1);
screen2.setCreatedBy(user);
screen2.setLastUpdatedBy(user);
ScreenInfoPojo screen3=new ScreenInfoPojo();
screen3.setId(3l);
screen3.setName("Screen3");
screen3.setParentScreen(Screen2);
screen3.setCreatedBy(user);
screen3.setLastUpdatedBy(user);
ScreenInfoPojo screen4=new ScreenInfoPojo();
screen4.setId(4l);
screen4.setName("Screen4");
screen4.setParentScreen(Screen3);
screen4.setCreatedBy(user);
screen4.setLastUpdatedBy(user);
List<ScreenInfoPojo> screens=new ArrayList<>();
screens.add(screen1);
screens.add(screen2);
screens.add(screen3);
screens.add(screen4);
ObjectMapper mapper = new ObjectMapper().registerModule(new JsonViewModule());
String json = mapper.writeValueAsString(JsonView.with(screens).onClass(ScreenInfoPojo.class, Match.match()
.exclude("*")
.include("id","name","createdBy.name","lastUpdatedBy.mobileNo","parentScreen.id")));
System.out.println("json"+json);
}
# Result
[{
"id": 1,
"name": "Screen1",
"parentScreen": null,
"createdBy": {
"name": "ABC"
},
"lastUpdatedBy": {
"mobileNo": "123456789"
}
}, {
"id": 2,
"name": "Screen2",
"parentScreen": {
"id": 1,
"name": "Screen1",
"parentScreen": null,
"createdBy": {},
"lastUpdatedBy": {}
},
"createdBy": {
"name": "ABC"
},
"lastUpdatedBy": {
"mobileNo": "123456789"
}
}, {
"id": 3,
"name": "Screen3",
"parentScreen": {
"id": 2,
"name": "Screen2",
"parentScreen": {
"id": 1,
"name": "Screen1",
"parentScreen": null,
"createdBy": {},
"lastUpdatedBy": {}
},
"createdBy": {},
"lastUpdatedBy": {}
},
"createdBy": {
"name": "ABC"
},
"lastUpdatedBy": {
"mobileNo": "123456789"
}
}, {
"id": 4,
"name": "Screen4",
"parentScreen": {
"id": 3,
"name": "Screen3",
"parentScreen": {
"id": 2,
"name": "Screen2",
"parentScreen": {
"id": 1,
"name": "Screen1",
"parentScreen": null,
"createdBy": {},
"lastUpdatedBy": {}
},
"createdBy": {},
"lastUpdatedBy": {}
},
"createdBy": {},
"lastUpdatedBy": {}
},
"createdBy": {
"name": "ABC"
},
"lastUpdatedBy": {
"mobileNo": "123456789"
}
}]
#Expected Result
[{
"id": 1,
"name": "Screen1",
"parentScreen": null,
"createdBy": {
"name": "ABC"
},
"lastUpdatedBy": {
"mobileNo": "123456789"
}
}, {
"id": 2,
"name": "Screen2",
"parentScreen": {
"id": 1
},
"createdBy": {
"name": "ABC"
},
"lastUpdatedBy": {
"mobileNo": "123456789"
}
}, {
"id": 3,
"name": "Screen3",
"parentScreen": {
"id": 2
},
"createdBy": {
"name": "ABC"
},
"lastUpdatedBy": {
"mobileNo": "123456789"
}
}, {
"id": 4,
"name": "Screen4",
"parentScreen": {
"id": 3
},
"createdBy": {
"name": "ABC"
},
"lastUpdatedBy": {
"mobileNo": "123456789"
}
}]
#Problem
In my use case I have a class ScreenInfoPojo which refers to same class as parentScreen ,
I am trying to fetch specific field/fields of parent ( "parentScreen.id") instate I am getting all fields that I have defined on child/target Object ("id","name","createdBy.name","lastUpdatedBy.mobileNo","parentScreen.id") and parent response is again recursive ! One thing i observed that It is only happening in case of a class has its own reference , I placed User class reference as two different field createdBy and lastUpdatedBy and tried to fetch "name" and "mobileNo" respectively worked just fine.
Can you suggest any solution for this problem?
Thanks
I'm using this in a Spring (Boot) application so have followed the instructions to create the JsonViewSupportFactoryBean Bean however its not excluding the excluded entity field at all. The excluded field is a reference to another domain entity.
Here is the entity:
`public class Attitudestate
implements java.io.Serializable,
UniquelyIdentified
{
private Long id;
private Runcatalog runidentity;
private Integer runidentityId;
private Double gpstime;
private Date utctimestamp;
private transient Double[] attitude;
private Float attitudeerror;
private Float currentangularrate;
private Float angularrateerror;
@JoinColumn(name = "runidentity", nullable = false)
@ManyToOne(fetch = FetchType.LAZY)
@XmlTransient
public Runcatalog getRunidentity()
{
return this.runidentity;
}
public void setRunidentity(Runcatalog runidentity)
{
this.runidentity = runidentity;
}`
In my controller I have:
`private JsonResult json = JsonResult.instance();
public Page findByRunIdentityId(Integer runidentityId, Pageable pageable)
{
Page attitudestates = repository.findByRunIdentityId(runidentityId, pageable);
return json.use(JsonView.with(attitudestates)
.onClass(Attitudestate.class, Match.match()
.exclude("runidentity")))
.returnValue();
}`
However the resulting REST response has the runidentity instance which by the way contains a reference to Attitudestate. I want to simply ignore runidentity in the REST response as it already has runidentityId. I can do this with which I can do with @JsonIgnore in the entity but I would prefer to not change my entities.
Hi, I like your library but if I use it with "lazy" relationships, I always see the next error:
"Could not write content: failed to lazily initialize a collection of role...."
I add the Hibernate5Module in the config file (adding a new converter of type MappingJackson2HttpMessageConverter) to avoid this problem when JSON serializes my class with lazy loads.
But when I add your Bean "JsonViewSupportFactoryBean views()", I get the error.
Then, my question is if it is possible to use your library with lazy loads (and Hibernate5Module), because I need exclude some properties and ignore, or load with a null value, a lazy property.
Thanks for all, and sorry for my English.
All values on TestObject
will be excluded if you specify a matcher like this on another class:
TestObject ref = new TestObject();
ref.setStr1("str");
ref.setInt1(3);
TestSubobject sub = new TestSubobject();
sub.setVal("val1");
sub.setOtherVal("val2");
ref.setSub(sub);
String serialized = sut.writeValueAsString(JsonView.with(ref).onClass(TestSubobject.class, match()
.exclude("*")
.include("otherVal")));
Currently, if we've excluded all fields from a response and are only specifying included fields, in order to include all fields of a nested object, we must qualify it with the .* notation. One minor improvement I'd like to request would be to implicitly derive that when just using the object name.
So, if I have objects:
class MyObject {
List<NestedObject> nested = new ArrayList<>();
...
}
class NestedObject {
String value = UUID.randomUUID().toString();
...
}
We have to use the include fields 'nested.*'. It would be great if we could just use 'nested' to accomplish the same thing.
Matchers defined on interfaces are never used. The serializer should attempt to match on the interfaces for each class in the hierarchy. Interfaces cannot have fields, but the match should still work and the exclusion/inclusion should be attempted on the supplied object.
It seems that if I use a wildcard inclusion on an object, but then add a qualified exclusion on one of it's properties, that exclusion will be ignored. It would be great if the more qualified inclusion/exclusion would take precedent over a wildcard.
I know this use case is a bit simple, but with the following:
class User {
private Name name;
...
}
class Name {
private String firstName = "John";
private String lastName = "Doe";
private String middleName = "Robert";
private String suffix = "III";
...
}
This would return everything except the middle name:
JsonResult.instance()
.use(JsonView.with(new User())
.onClass(User.class, Match.match()
.include("name.*")
.exclude("name.middleName")
));
Just let me know if that isn't clear enough.
Once again, great work on this project!
To make it easier to instantiate the serializer, it would be nice if there was a SimpleModule implementation available. That would make it possible to do the following:
ObjectMapper mapper = new ObjectMapper().registerModule(new JsonViewModule());
Hi thank you for writing a great utility. I want nulls in my json, I want to see all fields. How do I configure the API to return nulls just like Jackson normally does when a serialize a class?
Hello!
Congratulations on the project.
Is there any way to perform JAX-RS integration.
Hi
Thanks for the work.
The dates are always output as integer.
A nice feature would be to use the date formatter supplied in the ObjectMapper by the client.
For instance:
mapper.setDateFormat(new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZ"));
I see that you added the support for this but, as far as I could see, the new code is not already released.
Is it correct ? Do you have a date planned for a new release ?
Have a good day
Hi,
Really nice library, but regarding Spring integration and Dates' formatting, I'm suffering some lacks of customization.
When integrating with Spring Boot, Jackson configuration is ignored. This is what I've in my application.properties
which works when not using the JsonView library:
# Jackson serialization config
spring.jackson.serialization.WRITE_DATES_AS_TIMESTAMPS = false
spring.jackson.date-format = dd-MM-yyyy HH:mm:ss
So, my question is... there any way to use the ObjectMapper configured and instantiated by Spring when parsing the objects? Even I've tried to instantiate a custom ObjectMapper and pass it to the @bean when configuring the JsonViewSupportFactoryBean, instead of using the default mapper, something like:
@Bean
public JsonViewSupportFactoryBean views() {
ObjectMapper mapper = new ObjectMapper();
mapper.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false);
mapper.setDateFormat(new SimpleDateFormat("dd-MM-yyyy HH:mm:ss"));
return new JsonViewSupportFactoryBean(mapper);
}
But it didn't work. Dates are shown as numbers like timestamps.
I think there are customizations like date formatting which have been ignored, and it would be really nice if they could be taken into account here. Is it possible?
Thanks!
Man, I must say, what you've produced here is great! I was able to wire this into an API I've been working on, and intercept every request to allow end users to pass in which fields they would like back. After all said and done, there was no need to hand code anything with the JsonView within any controllers.
One thing that I noticed (which is actually a feature of JsonView) is that including all fields (using an asterisk) actually serializes XmlTransient and JsonIgnore attributes back in the response. However, this can be very problematic when comparing JSON results with generated Swagger docs, and/or extending third party framework objects such as Spring's ResourceSupport for HATEOAS.
What would be great is if we had the capability to disable this feature using the JsonResult. So, we'd return all fields, but not those that were marked to be ignored.
Hi all,
I have established two tests that have different views. When I run either one of the tests, everything works perfectly fine. But when I run both tests after each other the second test always fails. One additoinal point: As I found out, in case the second view contains less(!) exclusions then the first test case, then there will be an error, too. When I include additional exclusions, the second test works. This is particularly the case when I exclude in the first test a complete sub-object (e.g. claims) and in the second test I only exclude a subset of claims, e.g. "claims.individuellevorgaenge". This will fail then as I exclude less then in the first test.
So, in the first test I exclude:
"metadata", "fristen.vorgang", "claim.individuellevorgaenge","claim.individuelleschaeden"
in the second the fields
"claim", "fristen", "metadata"
Under these circumstances the test fails. In case I run the second test first (excluding: claim, fristen, metadata) then the second test succeedes. What is happening here?
The error that is shown when the test fails is:
java.lang.StackOverflowError
at java.util.regex.Pattern.compile(Pattern.java:1683)
at java.util.regex.Pattern.(Pattern.java:1351)
at java.util.regex.Pattern.compile(Pattern.java:1028)
at java.lang.String.replaceAll(String.java:2223)
at com.monitorjbl.json.JsonViewSerializer$JsonWriter.lambda$containsMatchingPattern$0(JsonViewSerializer.java:459)
at com.monitorjbl.json.Memoizer.lambda$matches$1(Memoizer.java:31)
at java.util.concurrent.ConcurrentHashMap.computeIfAbsent(ConcurrentHashMap.java:1660)
at com.monitorjbl.json.Memoizer.matches(Memoizer.java:31)
at com.monitorjbl.json.JsonViewSerializer$JsonWriter.containsMatchingPattern(JsonViewSerializer.java:456)
at com.monitorjbl.json.JsonViewSerializer$JsonWriter.fieldAllowed(JsonViewSerializer.java:375)
at com.monitorjbl.json.JsonViewSerializer$JsonWriter.writeObject(JsonViewSerializer.java:302)
at com.monitorjbl.json.JsonViewSerializer$JsonWriter.write(JsonViewSerializer.java:407)
at com.monitorjbl.json.JsonViewSerializer$JsonWriter.writeObject(JsonViewSerializer.java:314)
at com.monitorjbl.json.JsonViewSerializer$JsonWriter.write(JsonViewSerializer.java:407)
at com.monitorjbl.json.JsonViewSerializer$JsonWriter.writeObject(JsonViewSerializer.java:314)
at com.monitorjbl.json.JsonViewSerializer$JsonWriter.write(JsonViewSerializer.java:407)
at com.monitorjbl.json.JsonViewSerializer$JsonWriter.writeObject(JsonViewSerializer.java:314)
at com.monitorjbl.json.JsonViewSerializer$JsonWriter.write(JsonViewSerializer.java:407)
at com.monitorjbl.json.JsonViewSerializer$JsonWriter.writeObject(JsonViewSerializer.java:314)
at com.monitorjbl.json.JsonViewSerializer$JsonWriter.write(JsonViewSerializer.java:407)
at com.monitorjbl.json.JsonViewSerializer$JsonWriter.writeObject(JsonViewSerializer.java:314)
at com.monitorjbl.json.JsonViewSerializer$JsonWriter.write(JsonViewSerializer.java:407)
at com.monitorjbl.json.JsonViewSerializer$JsonWriter.writeObject(JsonViewSerializer.java:314)
at com.monitorjbl.json.JsonViewSerializer$JsonWriter.write(JsonViewSerializer.java:407)
at com.monitorjbl.json.JsonViewSerializer$JsonWriter.writeObject(JsonViewSerializer.java:314)
at com.monitorjbl.json.JsonViewSerializer$JsonWriter.write(JsonViewSerializer.java:407)
at com.monitorjbl.json.JsonViewSerializer$JsonWriter.writeObject(JsonViewSerializer.java:314)
at com.monitorjbl.json.JsonViewSerializer$JsonWriter.write(JsonViewSerializer.java:407)
at com.monitorjbl.json.JsonViewSerializer$JsonWriter.writeObject(JsonViewSerializer.java:314)
at com.monitorjbl.json.JsonViewSerializer$JsonWriter.write(JsonViewSerializer.java:407)
at com.monitorjbl.json.JsonViewSerializer$JsonWriter.writeObject(JsonViewSerializer.java:314)
....
Has anyone a clue what the problem could be?
I don't want to always have to specify everything I want to include. It would be nice if I could do this instead:
JsonView.with(obj)
.onClass(TestObject.class, Match.match()
.exclude("*")
.include("id")
.include("name"))
I'm trying to remove one field from a list, like this
User user = userRepository.findByBackendAccessToken(token);
Set<Room> res = json.use(JsonView.with(user.getRooms()).onClass(Room.class, match().exclude("users"))).returnValue();
but when I get an exception at this point. here is the output:
[2016-05-30 22:54:51.437] boot - 9379 WARN [qtp216065821-18] --- ServletHandler:
org.springframework.web.util.NestedServletException: Handler processing failed; nested exception is java.lang.StackOverflowError
at org.springframework.web.servlet.DispatcherServlet.triggerAfterCompletionWithError(DispatcherServlet.java:1305)
at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:979)
at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:895)
at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:967)
at org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:858)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:687)
at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:843)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:790)
at org.eclipse.jetty.servlet.ServletHolder.handle(ServletHolder.java:812)
at org.eclipse.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1669)
at org.eclipse.jetty.websocket.server.WebSocketUpgradeFilter.doFilter(WebSocketUpgradeFilter.java:224)
at org.eclipse.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1652)
at org.springframework.boot.actuate.autoconfigure.EndpointWebMvcAutoConfiguration$ApplicationContextHeaderFilter.doFilterInternal(EndpointWebMvcAutoConfiguration.java:261)
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
at org.eclipse.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1652)
at com.inkdrop.config.web.TokenAuthenticationFilter.doFilter(TokenAuthenticationFilter.java:59)
at org.eclipse.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1652)
at com.inkdrop.config.web.SimpleCORSFilter.doFilter(SimpleCORSFilter.java:33)
at org.eclipse.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1652)
at org.springframework.boot.actuate.trace.WebRequestTraceFilter.doFilterInternal(WebRequestTraceFilter.java:115)
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
at org.eclipse.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1652)
at org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:121)
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
at org.eclipse.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1652)
at org.springframework.boot.actuate.autoconfigure.MetricsFilter.doFilterInternal(MetricsFilter.java:103)
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
at org.eclipse.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1652)
at org.eclipse.jetty.servlet.ServletHandler.doHandle(ServletHandler.java:585)
at org.eclipse.jetty.server.handler.ScopedHandler.handle(ScopedHandler.java:143)
at org.eclipse.jetty.security.SecurityHandler.handle(SecurityHandler.java:577)
at org.eclipse.jetty.server.session.SessionHandler.doHandle(SessionHandler.java:223)
at org.eclipse.jetty.server.handler.ContextHandler.doHandle(ContextHandler.java:1127)
at org.eclipse.jetty.servlet.ServletHandler.doScope(ServletHandler.java:515)
at org.eclipse.jetty.server.session.SessionHandler.doScope(SessionHandler.java:185)
at org.eclipse.jetty.server.handler.ContextHandler.doScope(ContextHandler.java:1061)
at org.eclipse.jetty.server.handler.ScopedHandler.handle(ScopedHandler.java:141)
at org.eclipse.jetty.servlets.gzip.GzipHandler.handle(GzipHandler.java:479)
at org.eclipse.jetty.server.handler.HandlerWrapper.handle(HandlerWrapper.java:97)
at org.eclipse.jetty.server.Server.handle(Server.java:499)
at org.eclipse.jetty.server.HttpChannel.handle(HttpChannel.java:311)
at org.eclipse.jetty.server.HttpConnection.onFillable(HttpConnection.java:257)
at org.eclipse.jetty.io.AbstractConnection$2.run(AbstractConnection.java:544)
at org.eclipse.jetty.util.thread.QueuedThreadPool.runJob(QueuedThreadPool.java:635)
at org.eclipse.jetty.util.thread.QueuedThreadPool$3.run(QueuedThreadPool.java:555)
at java.lang.Thread.run(Thread.java:745)
Caused by: java.lang.StackOverflowError
at java.util.regex.Pattern.compile(Pattern.java:1683)
at java.util.regex.Pattern.<init>(Pattern.java:1351)
at java.util.regex.Pattern.compile(Pattern.java:1028)
at java.lang.String.replaceAll(String.java:2223)
at com.monitorjbl.json.JsonViewSerializer$JsonWriter.containsMatchingPattern(JsonViewSerializer.java:332)
at com.monitorjbl.json.JsonViewSerializer$JsonWriter.fieldAllowed(JsonViewSerializer.java:294)
at com.monitorjbl.json.JsonViewSerializer$JsonWriter.writeObject(JsonViewSerializer.java:242)
at com.monitorjbl.json.JsonViewSerializer$JsonWriter.write(JsonViewSerializer.java:348)
at com.monitorjbl.json.JsonViewSerializer$JsonWriter.writeObject(JsonViewSerializer.java:245)
at com.monitorjbl.json.JsonViewSerializer$JsonWriter.write(JsonViewSerializer.java:348)
at com.monitorjbl.json.JsonViewSerializer$JsonWriter.writeList(JsonViewSerializer.java:154)
at com.monitorjbl.json.JsonViewSerializer$JsonWriter.write(JsonViewSerializer.java:347)
at com.monitorjbl.json.JsonViewSerializer$JsonWriter.writeObject(JsonViewSerializer.java:245)
at com.monitorjbl.json.JsonViewSerializer$JsonWriter.write(JsonViewSerializer.java:348)
at com.monitorjbl.json.JsonViewSerializer$JsonWriter.writeObject(JsonViewSerializer.java:245)
at com.monitorjbl.json.JsonViewSerializer$JsonWriter.write(JsonViewSerializer.java:348)
at com.monitorjbl.json.JsonViewSerializer$JsonWriter.writeList(JsonViewSerializer.java:154)
at com.monitorjbl.json.JsonViewSerializer$JsonWriter.write(JsonViewSerializer.java:347)
at com.monitorjbl.json.JsonViewSerializer$JsonWriter.writeObject(JsonViewSerializer.java:245)
at com.monitorjbl.json.JsonViewSerializer$JsonWriter.write(JsonViewSerializer.java:348)
at com.monitorjbl.json.JsonViewSerializer$JsonWriter.writeObject(JsonViewSerializer.java:245)
I'm using Spring Boot 1.3.5.
I have a code that does a include on a object as below. match.exclude("*").include("venkat.displayName").include("venkat.status").include("venkat.id").include("venkat.description");
json.use(JsonView.with(classObject).onClass(clazz, match));
venkat's structure looks like this:
"venkat" : [{ }, {}]
It has completely eliminated and returned { } instead of keeping the fields for include.
Hi
Your library does exactly what we were looking for. However, we've noticed enabling it changes our BigDecimal field JSON from:
"latitude": 9874359834.345,
to:
"latitude": { "intVal": null, "scale": 3, "precision": 13, "stringCache": null, "intCompact": 9874359834345 },
How can we restore it back to the initial version?
Thanks
Hi,
is it right that the JsonViewSupportFactoryBean replaces all other converters in
https://github.com/monitorjbl/json-view/blob/master/spring-json-view/src/main/java/com/monitorjbl/json/JsonViewSupportFactoryBean.java#L33 ?
Then in
https://github.com/monitorjbl/json-view/blob/master/spring-json-view/src/main/java/com/monitorjbl/json/JsonViewSupportFactoryBean.java#L40
the converter is added again?!
How about just replacing a possibly existing MappingJackson2HttpMessageConverter instead?
Now my application misses the Jaxb2RootElementHttpMessageConverter which it had before.
Thanks for this work so far.
Best regards
Achim
If I want to be able to use the serializer outside of SpringMVC, I have to include a lot of Spring-related classes in my project. The serializer portion should be separate from the Spring MVC integration.
A declarative, efficient, and flexible JavaScript library for building user interfaces.
๐ Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. ๐๐๐
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google โค๏ธ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.