gpt4 book ai didi

java - 在 Jboss EAP 7.2.0.GA 中处理 JSON 序列化

转载 作者:搜寻专家 更新时间:2023-11-01 01:59:17 25 4
gpt4 key购买 nike

在我的 Jboss 中,我尝试使用 JAX-RS 实现 REST 服务。它应该返回某个对象的 JSON 序列化版本

 @GET
@Produces({ MediaType.APPLICATION_JSON })
public BlacklistDTO getByName(
@QueryParam("gav") final List<String> gavStringList)
{
...
}

对象的某些部分没有正确序列化(结果为空)。我如何处理/自定义 Jboss 生成 JSON 的方式?

最佳答案

您可以自定义实用程序的配置以序列化/反序列化 JSON(通常是 EAP 中包含的 Jackson),并配置/注册模块到 Jackson,指示如何对复杂对象执行此工作。

如果您使用的是 CDI + Resteasy + Jackson,您可以:

  1. 提供一个 JAX-RS 自定义 Json 提供程序,您可以在其中使用自定义配置配置 Jackson ObjectMapper。例如。

    @Provider
    @Produces(MediaType.APPLICATION_JSON)
    public class CustomJsonProvider implements ContextResolver<ObjectMapper> {
    private final ObjectMapper mapper;

    public CustomJsonProvider() {
    ObjectMapper mapperCdi = null;
    //if you are using CDI and you have your own Custom Object Mapper...
    BeanManager bm = CDI.current().getBeanManager();
    Set<Bean<?>> sBeans = bm.getBeans(ObjectMapper.class);
    if (sBeans != null && !sBeans.isEmpty()) {
    @SuppressWarnings("unchecked")
    Bean<ObjectMapper> bean = (Bean<ObjectMapper>) sBeans.iterator().next();
    CreationalContext<ObjectMapper> ctx = bm.createCreationalContext(bean);
    mapperCdi = (ObjectMapper) bm.getReference(bean, ObjectMapper.class, ctx);
    }
    if (mapperCdi != null) {
    mapper = mapperCdi;
    }else {
    //if you are not using CDI, you can create your own Custom Object Mapper or get it from a factory e.g you can do here AppConfig.getObjectMapperInstance() or create a new one
    mapper = new ObjectMapper();
    //eg. configuration of Hibernate 5 - Jackson Module
    Hibernate5Module h5m = new Hibernate5Module();
    h5m.configure(Hibernate5Module.Feature.SERIALIZE_IDENTIFIER_FOR_LAZY_NOT_LOADED_OBJECTS, true);
    mapper.registerModule((com.fasterxml.jackson.databind.Module) h5m);

    mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false)
    .configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, true);
    mapper.setSerializationInclusion(Include.NON_NULL);

    //eg. custom Jackson SimpleModule registration
    SimpleModule module = new SimpleModule("PaginationModule") {
    private static final long serialVersionUID = 1L;

    @Override
    public void setupModule(SetupContext context) {
    context.addAbstractTypeResolver(
    new SimpleAbstractTypeResolver().addMapping(Slice.class, SliceClientImpl.class));
    context.addAbstractTypeResolver(
    new SimpleAbstractTypeResolver().addMapping(Page.class, PageClientImpl.class));
    }
    };
    mapper.registerModule(module);
    }
    }

    @Override
    public ObjectMapper getContext(Class<?> objectType) {
    return mapper;
    }
    }
  2. 如果您使用 CDI,请定义您的“生产者”方法 (@Produce) 和您的 Jackson ObjectMapper 工厂:

    @ApplicationScoped
    public class AppConfig {
    private static ObjectMapper objectMapper;
    // Jackson Object Mapper
    @Produces
    public ObjectMapper createMapper() {
    return AppConfig.getObjectMapperInstance();
    }

    public static ObjectMapper getObjectMapperInstance() {
    if (objectMapper == null) {
    objectMapper = new ObjectMapper();

    //eg. configuration of Hibernate 5 - Jackson Module
    //Hibernate5Module h5m = new Hibernate5Module();
    //h5m.configure(Hibernate5Module.Feature.SERIALIZE_IDENTIFIER_FOR_LAZY_NOT_LOADED_OBJECTS, true);
    //objectMapper.registerModule((com.fasterxml.jackson.databind.Module) h5m);

    //eg. configuration of Joda - Jackson Module
    objectMapper.registerModule(new JodaModule());
    objectMapper.setTimeZone(TimeZone.getDefault());
    objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false)
    .configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false);
    objectMapper.setSerializationInclusion(Include.NON_NULL);

    //eg. custom Jackson SimpleModule registration
    SimpleModule module = new SimpleModule("PaginationModule") {
    private static final long serialVersionUID = 1L;
    @Override
    public void setupModule(SetupContext context) {
    context.addAbstractTypeResolver(
    new SimpleAbstractTypeResolver().addMapping(Slice.class, SliceClientImpl.class));
    context.addAbstractTypeResolver(
    new SimpleAbstractTypeResolver().addMapping(Page.class, PageClientImpl.class));
    }
    };
    objectMapper.registerModule(module);

    }
    return objectMapper;
    }
    }
  3. 检查您的提供商是否已通过 Jax-rs/Resteasy 注册:

如果您的 jackson 配置未注册,请尝试将以下行添加到您的 web.xml 中的上下文中:

<context-param>

<param-name>resteasy.providers</param-name>

<param-value>your.package.CustomJsonProvider</param-value>

</context-param>

有时,需要配置为服务提供者,添加一个文件“META-INF/services/javax.ws.rs.ext.Providers”(或者在 WEB-INF 中,具体取决于您使用 war 的包装类型, ear, jar, etc.) 内容如下:

your.package.CustomJsonProvider

以另一种方式,您可以返回一个String(或一个Response 对象),在您的服务中注入(inject)您的ObjectMapper(或您处理JSON 格式的实用程序)并创建/在返回语句之前序列化您的对象。

例如。使用 Json-b

@Path("/myservice")
public class MyService {

@POST
@Produces(MediaType.APPLICATION_JSON)
@Path("/resources")
public Response createJson(@FormParam("name") String name, @FormParam("surname") String surname) {
Response response;
User u = new User(name, surname);
Jsonb jsonb = JsonbBuilder.create();
String jsonString = jsonb.toJson(u);
response = Response.ok(jsonString).build();

return response;
}
}

例如。使用 json-b 以编程方式创建自定义 json

 // Create Json and serialize    
JsonObject json = Json.createObjectBuilder()
.add("name", "Falco")
.add("age", BigDecimal.valueOf(3))
.add("biteable", Boolean.FALSE).build(); String result = json.toString();

例如。使用 Jackson 以编程方式创建自定义 json

    ObjectMapper mapper = new ObjectMapper();
ArrayNode arrayNode = mapper.createArrayNode();
ObjectNode objectNode1 = mapper.createObjectNode();
objectNode1.put("name", "Anna");
objectNode1.put("surname", "T");
arrayNode.add(objectNode1);
ObjectNode objectNode2 = mapper.createObjectNode();
objectNode2.put("name", "John");
objectNode2.put("surname", "X");
arrayNode.add(objectNode2);

String json = arrayNode.toString();

希望对您有所帮助。

关于java - 在 Jboss EAP 7.2.0.GA 中处理 JSON 序列化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57759925/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com