programing

봄에 JSON 디시리얼라이저를 작성하거나 확장하기 위한 올바른 방법

javamemo 2023. 2. 24. 13:12
반응형

봄에 JSON 디시리얼라이저를 작성하거나 확장하기 위한 올바른 방법

봄에 커스텀 JSON 디시리얼라이저를 쓰려고 합니다.대부분의 필드에는 기본 직렬화기를 사용하고 몇 가지 속성에는 사용자 지정 직렬화기를 사용합니다.가능합니까?속성 대부분은 값이기 때문에 잭슨에게 디폴트 디시리얼라이저를 사용할 수 있습니다.다만, 참조가 되는 속성은 거의 없기 때문에, 커스텀 디시리얼라이저에서는, 데이타베이스에 참조명을 문의해, 데이타베이스로부터 참조치를 취득할 필요가 있습니다.

필요하다면 몇 가지 코드를 보여 드리겠습니다.

많은 것을 검색했는데, 지금까지 찾은 가장 좋은 방법은 이 기사입니다.

시리얼화할 클래스

package net.sghill.example;

import net.sghill.example.UserDeserializer
import net.sghill.example.UserSerializer
import org.codehaus.jackson.map.annotate.JsonDeserialize;
import org.codehaus.jackson.map.annotate.JsonSerialize;

@JsonDeserialize(using = UserDeserializer.class)
public class User {
    private ObjectId id;
    private String   username;
    private String   password;

    public User(ObjectId id, String username, String password) {
        this.id = id;
        this.username = username;
        this.password = password;
    }

    public ObjectId getId()       { return id; }
    public String   getUsername() { return username; }
    public String   getPassword() { return password; }
}

역직렬화 클래스

package net.sghill.example;

import net.sghill.example.User;
import org.codehaus.jackson.JsonNode;
import org.codehaus.jackson.JsonParser;
import org.codehaus.jackson.ObjectCodec;
import org.codehaus.jackson.map.DeserializationContext;
import org.codehaus.jackson.map.JsonDeserializer;

import java.io.IOException;

public class UserDeserializer extends JsonDeserializer<User> {

    @Override
    public User deserialize(JsonParser jsonParser, DeserializationContext deserializationContext) throws IOException {
        ObjectCodec oc = jsonParser.getCodec();
        JsonNode node = oc.readTree(jsonParser);
        return new User(null, node.get("username").getTextValue(), node.get("password").getTextValue());
    }
}

편집: 또는 새로운 버전의 com.fasterxml.jackson.databind를 사용하는 이 문서를 참조할 수 있습니다.JsonDeserializer 입니다.

하려고 했는데@Autowire스프링 매니지먼트의 서비스Deserializer누군가 잭슨에게 귀띔해줬는데newserializer/deserializer를 호출할 때 연산자를 지정합니다.이건 잭슨의 내 사건에 대한 자동 배선을 의미하지 않는다.Deserializer이렇게 할 수 있었어요.@Autowire서비스 클래스에서Deserializer:

context.xml

<mvc:annotation-driven>
  <mvc:message-converters>
    <bean class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter">
      <property name="objectMapper" ref="objectMapper" />
    </bean>
  </mvc:message-converters>
</mvc>
<bean id="objectMapper" class="org.springframework.http.converter.json.Jackson2ObjectMapperFactoryBean">
    <!-- Add deserializers that require autowiring -->
    <property name="deserializersByType">
        <map key-type="java.lang.Class">
            <entry key="com.acme.Anchor">
                <bean class="com.acme.AnchorDeserializer" />
            </entry>
        </map>
    </property>
</bean>

이제 나의Deserializer스프링 관리 콩, 자동 배선 작업입니다!

AnchorDeserializer.java

public class AnchorDeserializer extends JsonDeserializer<Anchor> {
    @Autowired
    private AnchorService anchorService;
    public Anchor deserialize(JsonParser parser, DeserializationContext context)
             throws IOException, JsonProcessingException {
        // Do stuff
    }
}

앵커 서비스자바

@Service
public class AnchorService {}

업데이트: 제가 이 글을 썼을 때 원래 답변은 효과가 있었지만, @xi.lin의 답변은 정확히 필요한 것입니다.잘 찾았어!

Spring MVC 4.2.1과 함께.RELEASE, Deserializer가 동작하려면 다음과 같이 새로운 Jackson2 의존관계를 사용해야 합니다.

사용하지 않음

<dependency>  
            <groupId>org.codehaus.jackson</groupId>  
            <artifactId>jackson-mapper-asl</artifactId>  
            <version>1.9.12</version>  
        </dependency>  

대신 이걸 쓰세요.

<dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-annotations</artifactId>
            <version>2.2.2</version>
        </dependency>
        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-core</artifactId>
            <version>2.2.2</version>
        </dependency>
        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-databind</artifactId>
            <version>2.2.2</version>
        </dependency>  

또한 사용com.fasterxml.jackson.databind.JsonDeserializer그리고.com.fasterxml.jackson.databind.annotation.JsonDeserialize의 클래스가 아닌 탈직렬화를 위해서org.codehaus.jackson

  1. 특정 속성에 대해 기본 역직렬라이저를 재정의하려면 다음과 같이 속성과 역직렬라이저를 표시할 수 있습니다.

--

// root json object
public class Example {
  private String name;
  private int value;
  // You will implement your own deserilizer/Serializer for the field below//
  @JsonSerialize(converter = AddressSerializer.class)
  @JsonDeserialize(converter = AddressDeserializer.class)
  private String address;
}

여기 완전한 예가 있습니다.

  1. Spring 어플리케이션 컨텍스트에서 비 스프링 관리 객체 매퍼를 사용하고 spring 관리 서비스를 사용하여 데이터베이스를 쿼리하도록 시리얼라이저/디시리얼라이저를 구성하는 경우, 이는 잭슨에게 다음을 사용하도록 지시함으로써 달성할 수 있습니다.Spring Handler instantiator역직렬화/직렬화 인스턴스(instance)를 만듭니다.

응용 프로그램콘텍스트 설정에서ObjectMapper을 가지고 놀다.SpringHandlerInstantiator예:

@Autowired
ApplicationContext applicationContext;

@Bean    
public ObjectMapper objectMapper(){
    Jackson2ObjectMapperBuilder builder = new Jackson2ObjectMapperBuilder();
    builder.handlerInstantiator(handlerInstantiator());
    // add additional configs, etc.. here if needed
    return builder.build();
}

@Bean
public HandlerInstantiator handlerInstantiator(){
    return new SpringHandlerInstantiator(applicationContext.getAutowireCapableBeanFactory());
}

그런 다음 objectMapper 위의 @Autowire를 사용하여 jserialize를 해제할 수 있습니다.

@Autowired
ObjectMapper objectMapper;

public Something readSomething(...){
    ...
    Something st = objectMapper.readValue(json, Something.class);
    ...
    return st;
}

필드 또는 에를 사용할 수 즉, @ bean bean bean by the @Autowire your services ( spring same by spring the by by the the the the the the the the the the the the the the the the the the the the ) ) 。ApplicationContext그 안에.

public class MyCustomDeserialiser extends ..{
      
    @Autowired;
    MyService service;

    @AutoWired
    SomeProperties properties;

    @Override
    public MyValue deserialize(JsonParser jp, DeserializationContext ctxt) throws IOException, JsonProcessingException {
    ....
    }
    ...
}

또한, Jackson deserialiser의 예를 여기에서 찾을 수 있습니다.

언급URL : https://stackoverflow.com/questions/11376304/right-way-to-write-json-deserializer-in-spring-or-extend-it

반응형