Where communities thrive


  • Join over 1.5M+ people
  • Join over 100K+ communities
  • Free without limits
  • Create your own community
People
Repo info
Activity
  • Jul 01 19:20
    Samathingamajig commented #921
  • Jul 01 13:55
    tgm1024 commented #1873
  • Jul 01 13:55
    tgm1024 commented #1873
  • Jul 01 13:54
    tgm1024 commented #1873
  • Jul 01 02:53
    cowtowncoder edited #2502
  • Jul 01 02:00

    cowtowncoder on master

    Fix #3503 - Implement Integer t… Update release notes wrt #3503 Merge branch '2.14' and 1 more (compare)

  • Jul 01 01:58
    cowtowncoder commented #3509
  • Jul 01 01:57

    cowtowncoder on 2.14

    Update release notes wrt #3503 (compare)

  • Jul 01 01:55
    cowtowncoder edited #3503
  • Jul 01 01:53
    cowtowncoder closed #3503
  • Jul 01 01:53

    cowtowncoder on 2.14

    Fix #3503 - Implement Integer t… (compare)

  • Jul 01 01:53
    cowtowncoder closed #3509
  • Jul 01 01:53
    cowtowncoder milestoned #3503
  • Jul 01 01:53
    cowtowncoder milestoned #3509
  • Jul 01 01:53
    cowtowncoder labeled #3509
  • Jul 01 01:43
    cowtowncoder commented #3530
  • Jul 01 01:34
    cowtowncoder commented #2502
  • Jul 01 01:32
    cowtowncoder edited #1995
  • Jul 01 01:31

    cowtowncoder on master

    Fix #3311: essentially backport… Merge branch '2.14' (compare)

  • Jul 01 01:31
    cowtowncoder commented #2502
Jeff Maxwell
@jmax01
During deserialization I need to convert any string that matches String.isBlank() to null. Is there a way to config the ObjectMapper to do this globally?
2 replies
Tatu Saloranta
@cowtowncoder
Jackson 2.13.0 is now FINALLY released
2 replies
lodhipr
@lodhipr

Hi, i need your help in parsing endpoint rest data to an object using restTemplate.getEntity()

As response Json data it has around 70 to 80 fields values , but i am interested in just 5 values , so it is useless to use objectMapper for 80 fields object then extracting 5 values. Is there another easy way to ignore the rest and convert 80 fields json to 5 variables object.

For Example:
"student:{
"name" : "ABC"
"age" : "20"
"address":
{
"place" : "XYZ"
"country" : "Russia"
"state" : "PQR"
}

form these json data i need to convert this to object as

public class Student
{
private String name;
private String country;
\getter and setter
}

please suggest me a better way to convert json to object.

currently I done some wrong way as
String jsonData = restTemplate.getObject(ENDPOINT,String.class)
Student stdObject = new Student();
JSONObject jsonObject = new JSONObject(jsonData);
stdObject.setName(jsonObject.getJSONObject("name"));

Tatu Saloranta
@cowtowncoder
You can just configure ObjectMapper to ignore unknown properties (mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);)
and read value into type:
Student s = mapper.readValue(json, Student.class);
2 replies
Chris
@codemedian

Hey folks. I'm trying to serialise a POJO to a JSON array. where the POJO has two properties, but I ant to serialise it into an array with three elements, the 2nd one being a placeholder. Any idea how to do this?

I tried

@JsonFormat(shape = JsonFormat.Shape.ARRAY)
@JsonPropertyOrder()
Pojo {
@JsonProperty(index = 0) String a;
@JsonProperty(index = 2)String b;
}

But that ends up as [a,b] serialised, when I need [a,null,b]

10 replies
James Howe
@OrangeDog
Can a Jackson developer help me out with a second opinion / backup on a related github issue?
10 replies
crstj6
@crstj6

Hi, let's say I define a DTO for representing response of one API endpoint. This DTO has around 10 fields and all of these fields are included during deserialization for my first API endpoint.

public class DummyResponseDto1 {
     @JsonProperty("id")
      private String id;
     // ...

Now, there is another API endpoint and its response schema is having some fields in common with the previous API endpoint. As I'm aware of DRY principle, I am trying to reuse the previous DTO via composition in the second DTO

public class DummyResponseDto2 {
      private DummyResponseDto1 dto;

The problem is that: not every field in DummyResponseDto1 will be used in the response of my second API endpoint, so I want to explicitly instruct Jackson ignore those fields. However, since DummyResponseDto1 is also used for my first API endpoint, I cannot simply modify it by adding @JsonIgnore because that would break the contract of my first API endpoint.

I'm seeking for advice on the best "Jackson" way to resolve this problem

6 replies
one solution I can think of is that, I explicitly set DummyResponseDto1 wrapped inside DummyResponseDto2 to be ignored, and adding some delegating getters w/ explicit @JsonProperty to have them included again
crstj6
@crstj6
public class DummyResponseDto2 {
    @JsonIgnore
    private DummyResponseDto1 dto;

    /**
     * Delegating getters
     */
    @JsonProperty("id")
    public String getId() {
        return dto.getId();
    }
}
However, this would 1) not null-safe 2) lots of boilerplate code
lambook
@lambook
Do you have a working example of fasterXml with subclasses deserialisation ?
in scala
lambook
@lambook
import _root_.com.fasterxml.jackson.databind.json.JsonMapper
import _root_.com.fasterxml.jackson.databind.{DeserializationFeature, JsonNode, Module, ObjectMapper, SerializationFeature}
import _root_.com.fasterxml.jackson.module.scala.DefaultScalaModule
import _root_.com.fasterxml.jackson.core.util.DefaultIndenter
import _root_.com.fasterxml.jackson.core.util.DefaultPrettyPrinter
import _root_.com.fasterxml.jackson.core.`type`.TypeReference
import _root_.com.fasterxml.jackson.annotation.JsonSubTypes
import _root_.com.fasterxml.jackson.annotation.JsonSubTypes.Type
import _root_.com.fasterxml.jackson.annotation.JsonTypeInfo

@JsonTypeInfo(
  use = JsonTypeInfo.Id.NAME,
  include = JsonTypeInfo.As.PROPERTY,
  property = "type"
)
@JsonSubTypes(value = Array(
  new Type(value = classOf[DatasList], name = "v1:datas")
))
class Result{
 val version: String ="2.0"
}

class Datas(node_id:String, address:String)

case class DatasList(var datas: List[Datas]) extends Result

def fromJsonToResult(json: String): Result=
{
  val  mapper  = JsonMapper.builder().addModule(DefaultScalaModule).build()
   val ref =  new TypeReference[Result] {}
    mapper.readValue(json,   ref)
}

object Test extends App {
  val mapper  = JsonMapper.builder().addModule(DefaultScalaModule).build()
  val str : String = """ {"datas":[{"id":"0041","address":"12545254"},{"id":"5455a5","address":"44544545"}]} """
  println(fromJsonToResult(str))
}
Runing this gives :

Exception in thread "main" java.lang.ExceptionInInitializerError
    at com.sample.Test.main(Test.scala)
Caused by: com.fasterxml.jackson.databind.exc.InvalidTypeIdException: Could not resolve subtype of [simple type, class com.sample.Result]: missing type id property 'type'
 at [Source: (String)" {"datas":[{"id":"0041","address":"12545254"},{"id":"5455a5","address":"44544545"}]} "; line: 1, column: 84]
any idea?
2 replies
crstj6
@crstj6

Is there a way to configure Mixin class at field level, and do it through annotation, rather than through ObjectMapper setting?
I'm looking for something like

public class JustAnotherDTO {
    // is this really possible?
   @JsonMixin(FirstDTOMixin.class)
    private FirstDTO dto

In this way, I can control what fields from FirstDTO to be included when FirstDTO is embedded within another DTO class, without directly modifying the source code of FirstDTO.

1 reply
lambook
@lambook
anyone have already faced this error:

at com.sample.TestJson.main(TestJson.scala)
Caused by: com.fasterxml.jackson.databind.exc.MismatchedInputException: Cannot deserialize value of type `java.lang.String` from Object value (token `JsonToken.START_OBJECT`)
 at [Source: (String)"{"value":"abc","valueSeq":["efg"]}"; line: 1, column: 1]
    at com.fasterxml.jackson.databind.exc.MismatchedInputException.from(MismatchedInputException.java:59)
    at com.fasterxml.jackson.databind.DeserializationContext.reportInputMismatch(DeserializationContext.java:1741)
    at com.fasterxml.jackson.databind.DeserializationContext.handleUnexpectedToken(DeserializationContext.java:1515)
    at com.fasterxml.jackson.databind.DeserializationContext.handleUnexpectedToken(DeserializationContext.java:1420)
    at com.fasterxml.jackson.databind.DeserializationContext.extractScalarFromObject(DeserializationContext.java:932)
    at com.fasterxml.jackson.databind.deser.std.StringDeserializer.deserialize(StringDeserializer
2 replies
TrickyDoodle
@TrickyDoodle
{
"foo":"foo",
"bar":${bar}
}
4 replies
Hey guys! Tell me please, is there a way to create a json without putting quotes for some values? Finally I need something like I posted above:
${bar} is a type double parameter which will be substituted later
liviu.vasut
@liviu.vasut:matrix.org
[m]
Hello, I'm writing a custom AnnotationIntrospector and while overriding the method findAndAddVirtualProperties() I encountered an issue with the names of the fields in the the List<BeanPropertyWriter> properties parameter. For example a field named aProp appears in that list as aprop. It appears that the culprit is com.fasterxml.jackson.databind.introspect.DefaultAccessorNamingStrategy#legacyManglePropertyName(). I would love to make a fix but I'm not exactly sure I'm aware of all the naming conventions to use when transforming getter names in field names. Can anyone advise on this?
2 replies
SimonM
@SimonM34
Why isn't jackson adding the @class tag? Could not resolve subtype of [simple type, class java.lang.Object]: missing type id property '@class'
1 reply
liviu.vasut
@liviu.vasut:matrix.org
[m]
5 replies
Hi @cowtowncoder , the above test reproduces the problem
(tested with jackson databind 2.14)
liviu.vasut
@liviu.vasut:matrix.org
[m]
You could say that I could have used the @JsonSerialize annotation for that, but this is a privacy library I'm working on that is meant for others to use across a platform, and the custom annotation is also used for other things like documentation and code generators
1 reply
dutchmahoney
@dutchmahoney
Hello. If I have an instance of JsonMapper, is there a way to tell if "default typing" is disabled? I'm trying to write a unit test to ensure some secure defaults, and while some of the other features are easy enough to test with isEnabled, I did not see an obvious approach for checking whether "default typing" is disabled or not.
3 replies
liviu.vasut
@liviu.vasut:matrix.org
[m]
@cowtowncoder: thanks for your input. I wasn't aware of the mix-in feature and although it won't help with my issue it's good to know for the future. But I'm not blocked by this, as I said I'm converting to lowercase as a workaround.
Ragnar Rova
@rrva
Hello! I am trying to optimize deserialization speed for some CBOR encoded data with jackson-dataformat-cbor. It seems to be one of the faster dataformats that jackson supports which still supports Map<K, V> types. I noticed that if I declare the classes I deserialize into as jvm records, the deserialization speed is drastically better than if I use kotlin data classes (with registerKotlinModule). Is this to be expected?
8 replies
Ragnar Rova
@rrva
Also, these are the optimizations I have done so far for deserialization speed. If anyone is aware of any low hanging fruit let me know: 1. Send all timestamps/dates/durations as numerical values. 2. Disable nanosecond precision on timestamps. 3. Use JsonFormat.Shape.ARRAY for all data classes. 4. Implement all Kotlin classes as jvm records (with @JvmRecord). 5. Use an objectReader with preconfigured forType. 6. Use Inputstream
5 replies
I can consider switching format if that speeds up things, but protobuf mapper does not seem to support Map<K, V> fields
Ragnar Rova
@rrva
Would be interesting to see if any of the learnings from https://www.infoq.com/presentations/simdjson-parser/ could be applied to jackson (https://github.com/simdjson/simdjson). I saw that a Vector API is at least coming to java https://openjdk.java.net/jeps/417 and there was some discussion here simdjson/simdjson#121
3 replies
李志博
@asasas234
I want to deserialize some classes that don't have a default constructor and are part of a framework that I can't modify, such as org.springframework.http.ResponseEntity. searching I learned that I can inherit from the DeserializationProblemHandler class and implement handleMissingInstantiator to solve this problem, but I'm not sure how to implement this method, is there a concrete example please?
4 replies
Rafał Hajdacki
@hajdamak
In case of deserialization to Java 16 record is there any way to distinguish between situation when JSON field is set to null and when field is not set at all. For example using jackson-databind-nullable or Java's Optional ?
9 replies
李志博
@asasas234
When I serialize a class without a default constructor, it reports (no Creators, like default construct, exist): cannot deserialize from Object value (no delegate- or property-based Creator) Is there any way I can tell if I can successfully deserialize the specified object? I tried calling objectMapper.canDeserialize and found that it always returns true
3 replies
pgouda89
@pgouda89

Hi Experts, I was using jersey 1.16 rest server using jackson 2.10.1 and things were fine.
Now I have upgraded jackson to use 2.13.1 and seeing the following error:

Caused by: com.sun.jersey.api.MessageException: A message body writer for Java class java.util.ArrayList, and Java type java.util.List<MYCLASS>, and MIME media type application/json was not found]. Check the service logs also for more information.
at java.lang.Thread.run(Thread.java:748)]. Check the service logs also for more information.
at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)]. Check the service logs also for more information.

Do we need to change any configuration to use default JSON object mapper?
1 reply
Ankush @dcodermobile
@ankush-dcoder

Hi guys, We are facing same issue as this. FasterXML/jackson-dataformats-text#190

Is there any solution? The emoji is turning into unicode in the textview on Android, instead of staying as emoji.

2 replies
pitr182
@pitr182
Hello all. I'm a little confused with the documentation for
ObjectMapper-setDateFormat
it states: ObjectMapper itself is only thread-safe when configuring methods (such as this one) are NOT called. Does this just mean it makes the object mapper non-thread-safe if this is called while the application is running/ serving traffic but it is safe to call this method to change the date format while the application is starting up as part of say a spring @Configuration class? Example of what would be done below:
import com.fasterxml.jackson.databind.util.StdDateFormat;
import org.springframework.boot.autoconfigure.jackson.Jackson2ObjectMapperBuilderCustomizer;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class JacksonConfig {

    @Bean
    public Jackson2ObjectMapperBuilderCustomizer jacksonObjectMapperBuilder() {
        return builder -> builder.dateFormat(new StdDateFormat().withColonInTimeZone(false));
    }
}
5 replies
Ramazan Sakin
@ramazansakin

Hi community,
I just didnt find any other specific room and here looks a general QA room.
I just want to share and understand a case:
I used @JsonManagedReference and @JsonBackReference first on my entities like:

image
and
image

and then when I try to add new airport, I got :
image

But when I try to switch the references, it worked properly. Also, when I add @JsonIgnore annotation any of entity, it also worked properly. From all above, what is the purpose of exact usage of @JsonManagedReference and @JsonBackReference ?

Thanks.

5 replies
smoomrik
@smoomrik

Hello everybody,
I was implementing object merging using @JsonMerge and @JsonSetter(nulls= Nulls.SKIP) at field level, and faced with a problem, it doesn't skip nulls in child objects. Maybe someone knows what I'm doing wrong and can help to point me in the right direction.

@NoArgsConstructor
    @Setter
    @Getter
    @AllArgsConstructor
    @Builder
    @JsonNaming(PropertyNamingStrategy.KebabCaseStrategy.class)
    public class Context {

        @NotNull
        @JsonMerge
        @JsonSetter(nulls = Nulls.SKIP)
        private FileProperties fileProperties;

        @NoArgsConstructor
        @AllArgsConstructor
        @Getter
        @Setter
        @JsonNaming(PropertyNamingStrategy.KebabCaseStrategy.class)
        public static class FileProperties {

            @NotEmpty
            @JsonMerge
            @JsonSetter(nulls = Nulls.SKIP)
            private String fileName;

            @NotNull
            @JsonMerge
            @JsonSetter(nulls = Nulls.SKIP)
            private String folderName;
        }
    }

And test

@SneakyThrows
    @Test
    public void testNullMerging() {
        // GIVEN
        var context = Context.builder()
            .fileProperties(new Context.FileProperties(
                "initialFileName",
                "initialFolderName"))
            .build();
        // AND
        var propertiesWithNulls = new HashMap<>();
        propertiesWithNulls.put("folder-name", null);
        propertiesWithNulls.put("file-name", "updatedFileName");
        var toMerge = new HashMap<>();
        toMerge.put("file-properties", propertiesWithNulls);
        // AND
        var mapper = new ObjectMapper();


        // WHEN
        Context mergedContext = mapper.readerForUpdating(context).readValue(mapper.writeValueAsString(toMerge));

        // THEN
        assertEquals("updatedFileName", mergedContext.getFileProperties().getFileName());
        assertEquals("initialFolderName", mergedContext.getFileProperties().getFolderName());
    }

I would appreciate any help here

7 replies
After debugging I found that it uses CreatorProperty instead of MergingSettableBeanProperty.
Tatu Saloranta
@cowtowncoder
Jackson 2.13.2 patch release starting now....
Simone Giusso
@SimoneGiusso

Hello! I would understand how Jackson serializes the Boolean wrapper in the following case:

public class Person {

     private String Name;

     private Boolean employeed;

     public Boolean getEmployeed() {
          return employeed;
     }

     public boolean isEmployeed() {
          return Boolean.TRUE.equals(employeed);
     }

}

Which method has higher priority is or get? If jackson uses get it means that the value serialized in JSON can be null, if it uses is this means that the value will be true or false since it returns a primitive. Would be nice attached a doc reference or point me out the code where shows how it works. It looks like this is not example in the java doc documentation. Thanks!

10 replies
wagnerdk
@wagnerdk

Hello, I'm unsure how to solve a problem with Jackson.

capability_types:
  tosca.capabilities.Container:
    derived_from: tosca.capabilities.Root
interface_types:
  node.lifecycle.Standard:
    derived_from: Root
    operations: 
        ...
relationship_types:
  HostedOn:
    description: 
        ...
node_types:
  TomcatType:
    description: Tomcat Webserver
    interfaces:
      lifecycle:
        type: node.lifecycle.Standard
        operations: 
            ...
    capabilities:
      containerCapability: tosca.capabilities.Container
topology_template:
  node_templates:
    TomcatContainer:
      type: TomcatType
    TomcatWebApp:
      type: WebAppType
      requirements:
        - host:
            node: TomcatContainer
            relationship: HostedOn

The yaml file has multiple parts where a value references to a map key. For example the ‘type’ in TomcatWebApp references to node_types -> TomcatType and the ‘node’ value in TomcatWebApp references to the TomcatContainer in the topology_template. Currently I read the referencing values as Strings but I would like them to be references to the Objects. I tried to use @JsonIdentityInfo but for example the TomcatType map entry in node_types does not know its name so how could jackson make the connection?

4 replies
Masinac
@Masinac

I'm trying to serialize to XML:
Expected:

<SystemName ExportDate="03/27/2022 21:05:22">
    <Order-21333 createdOn="03/27/2022 07:05:22">
        order content
    <Order-21333>
</SystemName>

Actual:

<SystemName ExportDate="03/27/2022 21:05:22">
    <order>
        <Order-21333 createdOn="03/27/2022 07:05:22">
            order content
        <Order-21333>
    </order>
</SystemName>

Classes:

@Data
@JacksonXmlRootElement(localName="SystemName")
public class OrderXMLRootDTO {

    @JacksonXmlProperty(isAttribute =  true, localName="ExportDate")
    private String exportDate = DateUtil.formatInstant(Instant.now(), "MM/dd/yyyy HH:mm:ss")

    @JsonSerialize(using = OrderSerializer.class)
    private OrderXMLDTO order;
}

@Data
public class OrderXMLDTO {

    @JsonIgnore
    private String orderId;

    other fields

}

public class OrderSerializer extends JsonSerializer<OrderXMLDTO> {
    @Override
    public void serialize(OrderXMLDTO value, JsonGenerator gen, SerializerProvider serializer) throws IOException {
        gen.writeStartObject();
        gen.writeObjectField("Order-" + value.getOrderId(), value);
    }
}

As you can see, I cannot get rid of that order wrapper. Can you please help?

4 replies
Ggg6542
@gusega
Hi here. I am struggling to make a factory object to be used for instantiating a java type from a json. I can make it work using the tree api, where I explicitly call that factory. But I would like to make it work with value api. To do this I need to somehow manually register that factory object as a deserializer/converter for my type. It seems that annotations do not allow specifying a factory object (instance). How do I do that?
3 replies
Tatu Saloranta
@cowtowncoder
Sebastien Bahloul
@sbahloul
Hello, I am working on various ISO standards and they are defining CDDL with numerical fields (instead of string field names). I read in the chat that it was not supported back in 2020. Is it something that changed ? And thank you a lot for the excellent job !
2 replies
Tatu Saloranta
@cowtowncoder
Jackson 2.12.7 (https://github.com/FasterXML/jackson/wiki/Jackson-Release-2.12.7) was released too -- no real changes since 2.12.6 except includes micro-patch 2.12.6.1 CVE fix for jackson-databind.
Released to simplify usage by those users who don't use jackson-bom (and/or don't understand how micropatches work :-( )
Daniel Andres Pelaez Lopez
@estigma88

Hi everyone, I have a backward-compatible problem with a JSON data, in a Kotlin project, before, we have the following:

data class TranscoderIngressStage(
    val id: String,
    val provider: String
)

That class generates the following JSON:

{
    "id": "123",
    "provider": "provider1",
}

Now, we want to add a new outputs attribute to the class as follows:

data class TranscoderIngressStage(
    val id: String,
    val provider: String,
    var outputs: List<TranscoderOutput>
)

data class TranscoderOutput(
    val id: String,
    val providerResourceId: String
)

If we try to deserialize the previous JSON that doesn't have the outputs property, it fails as the property is required.

Is there any Jackson annotation where I can say: if you don't find the JSON property, set the value as an empty list?

15 replies
Reece
@dragonaxe:waffle.tech
[m]
Hello Everyone!
Can anyone help explain why JsonContext.INSTANCE.verifySerializability(new ObjectMapper().readTree("{\"someNumber\": 5}")); fails with a comparison failure?
Debugging reveals that ObjectMapper::readTree() parses the 5 as an IntNode, but inside the call to verifySerializability a call to JsonContext::readValueFromBytes() re-parses the 5 as a LongNode.
Why does ObjectMapper and JsonContext produce differently typed numbers?
Reece
@dragonaxe:waffle.tech
[m]
Oops, the JsonContext class is from our internal code base, so please disregard my question.