logo
Tags down

shadow

Kafka's JsonDeserializer not working for java.util.Map


By : guest
Date : October 16 2020, 06:10 PM
With these it helps My strong suspicion would be that it is the polymorphic nature of your value rather than Maps per-se.
Spring is using Jackson underneath the hood for it's serialisation/deserialisation - and by default Jackson (in serialisation) when handling Object instances does not encode what class it is serialising.
code :
ObjectMapper.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
@Configuration
public class JacksonConfiguration {

 @Bean
 public ObjectMapper objectMapper() {
    ObjectMapper mapper = new ObjectMapper();
    #Your Configuration Here for example  mapper.configure(DeserializationFeature.something, true);

    return mapper;
 }
}


Share : facebook icon twitter icon

how to create a custom JsonDeserializer in Java?


By : Paddy
Date : March 29 2020, 07:55 AM
this will help I am a complete newbie with Jackson, but the following works for me.
First I add a JsonCreator method to A:
code :
public class A {
    private String a1;
    private Integer a2;
    public String getA1() { return a1; }
    public Integer getA2() { return a2; }
    public void setA1(String a1) { this.a1 = a1; }
    public void setA2(Integer a2) { this.a2 = a2; }

    @JsonCreator
    public static A fromJSON(String val) throws JsonParseException, JsonMappingException, IOException {
        ObjectMapper mapper = new ObjectMapper();
        A a = mapper.readValue(val,A.class);
        return a;
    }
} 
public class KeySerializer extends SerializerBase<Object> {
    private static final SerializerBase<Object> DEFAULT = new StdKeySerializer();

    private Set<Class<?>> objectKeys_ = Collections.synchronizedSet(new HashSet<Class<?>>());

    protected KeySerializer(Class<?>... objectKeys) {
        super(Object.class);
        for(Class<?> cl:objectKeys) {
            objectKeys_.add(cl);
        }
    }


    @Override
    public JsonNode getSchema(SerializerProvider provider, Type typeHint) throws JsonMappingException {
        return DEFAULT.getSchema(provider, typeHint);
    }


    @Override
    public void serialize(Object value, JsonGenerator jgen,
            SerializerProvider provider) throws IOException,
            JsonGenerationException {
        if (objectKeys_.contains(value.getClass())) {
            ObjectMapper mapper = new ObjectMapper();
            StringWriter writer = new StringWriter();
            mapper.writeValue(writer, value);
            jgen.writeFieldName(writer.toString());
        } else {
            DEFAULT.serialize(value, jgen, provider);
        }
    }
}
    ObjectMapper mapper = new ObjectMapper();
    StdSerializerProvider provider = new StdSerializerProvider();
    provider.setKeySerializer(new KeySerializer(A.class));
    mapper.setSerializerProvider(provider);

    StringWriter out = new StringWriter();
    mapper.writeValue(out, c);
    String json = out.toString();
    System.out.println("JSON= "+json);

    C c2 = mapper.readValue(json, C.class);
    System.out.print("C2= ");
    StringWriter outC2 = new StringWriter();
    mapper.writeValue(outC2, c2);
    System.out.println(outC2.toString());
JSON= {"c1":"goo","map":{"{\"a1\":\"1ccf\",\"a2\":7376}":{"b1":"5ox"},"{\"a1\":\"1cd2\",\"a2\":7379}":{"b1":"5p0"},"{\"a1\":\"1cd5\",\"a2\":7382}":{"b1":"5p3"},"{\"a1\":\"1cd8\",\"a2\":7385}":{"b1":"5p6"}}}
C2= {"c1":"goo","map":{"{\"a1\":\"1ccf\",\"a2\":7376}":{"b1":"5ox"},"{\"a1\":\"1cd2\",\"a2\":7379}":{"b1":"5p0"},"{\"a1\":\"1cd5\",\"a2\":7382}":{"b1":"5p3"},"{\"a1\":\"1cd8\",\"a2\":7385}":{"b1":"5p6"}}}

Calling custom JsonDeserializer from another JsonDeserializer


By : Olaf Johannes
Date : March 29 2020, 07:55 AM
Does that help In general, when writing a custom deserializer you need to make sure anything you can serialize with the ObjectMapper instead of actually parsing every field by itself. Once you do that, the ObjectMapper will automatically call the deserializer of an object if exists.
And the code:
code :
@JsonDeserialize(using = BobDeserializer.class)
class Bob {

    private Integer number;

    public Bob() {
    }

    public Integer getNumber() {
        return number;
    }

    public void setNumber(Integer number) {
        this.number = number;
    }
}

@JsonDeserialize(using = AliceDeserializer.class)
public class Alice {
    private Bob bob;

    public Alice() {
    }

    public Bob getBob() {
        return bob;
    }

    public void setBob(Bob bob) {
        this.bob = bob;
    }
}

class BobDeserializer extends StdDeserializer<Bob> {

    protected BobDeserializer() {
        super(Bob.class);
    }

    public Bob deserialize(JsonParser parser, DeserializationContext context) throws IOException {
        JsonNode node = parser.getCodec().readTree(parser);

        Integer number = node.get("number").asInt();

        Bob bob = new Bob();
        bob.setNumber(number);

        return bob;
    }
}

class AliceDeserializer extends StdDeserializer<Alice> {

    protected AliceDeserializer() {
        super(Alice.class);
    }

    public Alice deserialize(JsonParser parser, DeserializationContext context) throws IOException {
        JsonNode node = parser.getCodec().readTree(parser);

        ObjectMapper mapper = new ObjectMapper();
        Bob bob = mapper.readValue(node.get("bob").toString(), Bob.class);

        Alice alice = new Alice();
        alice.setBob(bob);

        return alice;
    }
}
Alice alice = new Alice();
Bob bob = new Bob();
bob.setNumber(3);
alice.setBob(bob);

ObjectMapper mapper = new ObjectMapper();

Alice alice1 = mapper.readValue(mapper.writeValueAsString(alice), Alice.class);

Spring cloud stream: Two different Kafkas in same app


By : Segrest
Date : March 29 2020, 07:55 AM
this will help You question is too general so I'd suggest to start by looking at Multibinder samples which include several variations including Kafka. There is more information and details on multiple binder support in reference manual.

I am seeing the error: A message body writer for Java class java.util.ArrayList, and Java type java.util.List<java.la


By : Jitendra Kumar
Date : March 29 2020, 07:55 AM
I wish did fix the issue. I see the JSON providers in the error message, so it seems you have the jersey-json dependency. But it seems (from what I tested) that the internal Jersey providers don't know how to handle lists of scalar values. For that you would need to make sure that Jackson is enabled. You can do that simply configuring the POJOMappingFeature in your web.xml

java.lang.NullPointerException: Attempt to invoke virtual method 'java.util.Iterator java.util.ArrayList


By : Konstantin Fedorov
Date : March 29 2020, 07:55 AM
help you fix your problem It looks like String s parameter is null, use logging to confirm. In such case Gson.fromJson() returns null as a result. Then you're trying to iterate through the list postList which is null and this results to NullPointerException.
Related Posts Related Posts :
  • Generating unique value in java give duplicate
  • How to fix 'handleWindowVisibility: no activity for token android.os.BinderProxy'?
  • Memory issue - InputStream/OutputStream
  • Download a .csv file Java6
  • Why NavigableSet JavaDoc states about implementation details?
  • How to create health check in Grafana?
  • What is the optimal way to call N blocking api calls in parallel to get most out of CPU while waiting for api calls to c
  • How to control text in edittext after key is pressed?
  • NullPointerException when starting a Popupwindow with default values set, otherwise it works
  • How to filter a dataset according to datetime values in Spark
  • RegEx for matching commas inside array values
  • Program won't continue when pressing enter. How do I fix this error?
  • Trying to increment counter using character comparison
  • Convert list into String with values
  • Avoiding major/minor version conflicts with Java/Maven dependencies
  • Lag a value with Datavec transform
  • Lower bound generic in java does not compile even when passing super class
  • Why CompletableFuture.runAsync is not executed?
  • How can I make the ball go where it is supposed to go after it is hit by the stick?
  • Spring -- allow overriding THAT particular bean only
  • Can i mock file.mkdirs() which is inside of a method
  • How to get .crt file from .jks
  • How to remove characters from String Value?
  • Unit Testing a Public method with private supporting methods inside of it?
  • JavaFX when button press draw rectangle with dimensions in textField and find if they intersect
  • pushing to hashmap of lists
  • Execution failed for task ':app:transformClassesAndResourcesWithR8ForRelease' while generating signed apk/bundle
  • log4j2 generates folder with older date - Springboot
  • Java casting mystery - Class.cast vs cast operator
  • Android sending notification from application A to application B
  • Libgdx Clearing Screen benefits
  • Asynchronous Lambda Proxy integration
  • Can't figure out why I'm getting java.lang.ArithmeticException: / by zero
  • How to create a non-blocking @RestController webservice in spring?
  • Fetching and downloading Maven artifacts programmatically
  • Java : A method which accepts a string as a parameter, what input validation would make the method defensible?
  • Why is it that the return statement in my method doesn't want to return a string?
  • How to flip two words in a sentence in java
  • Maven - How to remove module-info.class warning for shaded .jar?
  • Project Reactor, using a Flux sink outside of the creation lambda
  • Count the number of Arrays & access a specific array in the JSON Response using REST ASSURED with JAVA & Seleniu
  • Rotating zombies to face player
  • How to distribute the same apk for regular and instant app
  • How do I find one String inside of another
  • How to instantiate interface in Kotlin?
  • Java Intern pool implementation creates too many temporary objects
  • I need some advide about user type with hashmap
  • Is there a way to split for loop in java to do different things for values?
  • Thread safety on block of code which has external reference
  • I am unable to install java8 on my ubuntu gcp machine
  • Function returning blank string
  • Class Random Java: The method "roll()" is undefined for type Random. Why?
  • How to return value from the function without exiting from the function?
  • Getting wrong hours when Convert date without time to Milliseconds using SimpleDateFormat
  • Why we need Action Interface when all actions can be done with ActionsClass
  • How can I make this program run when it says could not find or load main class?
  • How to avoid duplicate node?
  • Everytime i run this recrusion algorithm, my variable is set to 0 how to solve it
  • Determine Whether JLabel Text is Being Cut Off?
  • Why is TomEE not able to create JMS connection factory resource?
  • shadow
    Privacy Policy - Terms - Contact Us © 35dp-dentalpractice.co.uk