Tag: jackson

基于spring的组动态POJOvalidation

考虑以下pojo以供参考: public class User{ private String username; private String firstName; private String middleName; private String lastName; private String phone; //getters and setters } 我的应用程序基本上是基于spring-boot的REST API,它暴露了两个端点,一个用于创建用户,另一个用于检索用户。 “用户”属于某些类别, group-a , group-b等,我从post请求的标题中获取。 我需要在运行时validation用户数据,validation可能会因用户组而异。 例如,属于组-a的用户可能将电话号码作为可选字段,而对于其他组可能是必填字段。 正则表达式也可能因组而异。 我需要能够配置spring,以某种方式动态validation我的pojo,一旦它们被创建,它们各自的validation集将根据它们的组触发。 也许我可以创建一个yml / xml配置,这将允许我启用它? 我宁愿不用@NotNull和@Pattern注释我的private String phone 。 我的配置如下: public class NotNullValidator implements Validator { private String group; private Object target; public String […]

用jackson反序列化枚举

我正在尝试并且没有用Jackson 2.5.4反序列化枚举,我在那里看不到我的情况。 我的输入字符串是驼峰式的,我想简单地映射到标准的Enum约定。 @JsonFormat(shape = JsonFormat.Shape.STRING) public enum Status { READY(“ready”), NOT_READY(“notReady”), NOT_READY_AT_ALL(“notReadyAtAll”); private static Map FORMAT_MAP = Stream .of(Status.values()) .collect(toMap(s -> s.formatted, Function.identity())); private final String formatted; Status(String formatted) { this.formatted = formatted; } @JsonCreator public Status fromString(String string) { Status status = FORMAT_MAP.get(string); if (status == null) { throw new IllegalArgumentException(string + ” […]

如何使用Jackson的objectMapper反序列化接口字段?

ObjectMapper的readValue(InputStream in, Class valueType)函数需要Class。 但是如果我在内部传递的类有一些接口作为数据成员,我该如何使用它。 虽然我可以理解这个exception背后的原因,因为jackson没有得到传递类的内部接口的具体类,但我的问题是如何解决它? 那我怎么反序列化呢? 我试图反序列化的类是: class BaseMetricImpl implements Metric { protected MetricValueDescriptor descriptor; } 这里MetricValueDescriptor是一个接口,所以这给了我以下错误: – com.fasterxml.jackson.databind.JsonMappingException: Can not construct instance of MetricValueDescriptor, problem: abstract types either need to be mapped to concrete types, have custom deserializer, or be instantiated with additional type information at [Source: java.io.ByteArrayInputStream@2ede2c9f; line: 1, column: 2] (through […]

如何使用java中的XPath / JsonPath更改json文件中的值

这是json文件 { “session”: { “name”:”JSESSIONID”, “value”:”5864FD56A1F84D5B0233E641B5D63B52″ }, “loginInfo”: { “loginCount”:77, “previousLoginTime”:”2014-12-02T11:11:58.561+0530″ } } 我想更改name.by的值直接给XPath / JsonPath Like ($.session.name).changevalue(“MYSESSINID”)这只是一个例子 我正确使用jackson库并使用以下代码通过XPath进行读取 ObjectMapper mapper = new ObjectMapper(); Object jsonObj=mapper.readValue(new File(Json file), Object.class); Object name=PropertyUtils.getProperty(jsonObj, “session.name”); System.out.println(“Name:”+name); 他们是一种通过XPath更改名称的方法 PropertyUtils.setProperty(jsonObj, “session.value”, “new value”); 仍然在文件中它无法正常工作。

Spring REST 3支持XML和JSON

如果我们使用Spring MVC开发REST,它将支持XML和JSON数据。 我在spring config bean app-servlet.xml编写了ContentNegotiationViewResorver 我的Spring REST控制器是: @Controller @RequestMapping(“/rest/customers”) class CustomerRestController { protected Log log = LogFactory.getLog(CustomerRestController.class); @RequestMapping(method = POST) @ResponseStatus(CREATED) public void createCustomer(@RequestBody Customer customer, HttpServletResponse response) { log.info(“>>>” + customer.getName()); response.setHeader(“Location”, String.format(“/rest/customers/%s”, customer.getNumber())); } @RequestMapping(value = “/{id}”, method = GET) @ResponseBody public Customer showCustomer(@PathVariable String id) { Customer c = new Customer(“0001”, […]

哪一个更轻,JSON还是BSON?

我编写了将对象序列化为JSON和BSON的代码。 根据我的输出,生成的BSON的大小比JSON大。 这是预期的吗? 从我的Bson.class代码 (使用Jackson和bson4jackson) private ByteArrayOutputStream baos = new ByteArrayOutputStream(); private BsonFactory fac = new BsonFactory(); private ObjectMapper mapper = new ObjectMapper(fac); public Bson(Object obj) throws JsonGenerationException, JsonMappingException, IOException { mapper.writeValue(baos, obj); } public int size() { return baos.size(); } public String toString() { byte[] bytes = baos.toByteArray(); return new String(bytes); } 来自我的Json.class private […]

(De-)在运行时以自定义方式序列化Bean

我们假设我有以下POJO: class Pojo { String s; Object o; Map m; } 在运行时,我想要除了一个属性之外的所有属性的默认序列化/反序列化。 通常,我想在序列化时用数据库中的ID替换字段,类似于其他问题 。 例如,我想用从外部映射获得的字符串替换o (例如: object1 “123”和object2 “456”): 序列化:读取o和替换(如果o是object1 ,则序列化为字符串“123”) 反序列化:读取“123”,查询某些表以获取o的原始值(即object1 ),用o = object1重新创建一个Pojo对象。 我知道模块将是一种方法,但我不知道如何使用它们同时保持自动BeanSerializer / Deserializer不需要更改的属性。 有人可以给出一个例子(甚至做作)或另类方法吗? 笔记: 我不能使用注释或Mixins,因为在编译时未知更改(即任何属性可能以不可确定的方式更改)。 另一个问题指向使用CustomSerializerFactory,它似乎可以完成这项工作。 不幸的是,官方网站表明它不再是推荐的方法 ,而是应该使用模块。 编辑 为了更清楚一点,我可以使用Mixins执行以下操作: ObjectMapper mapper = new ObjectMapper(MongoBsonFactory.createFactory()); mapper.addMixInAnnotations(Pojo.class, PojoMixIn.class); ObjectReader reader = mapper.reader(Pojo.class); DBEncoder dbEncoder = DefaultDBEncoder.FACTORY.create(); OutputBuffer buffer = new […]

使用Jackson JsonNodeFactory的最佳方式

我正在使用Jackson构建自定义JSON对象。 这是正确的方法吗? 它似乎工作得很好(输出是正确的)但我可能会错过我使用JsonNodeFactory的方式。 对象是否意味着像我在这里所做的那样传递? JsonNodeFactory factory = JsonNodeFactory.instance; ObjectNode dataTable = new ObjectNode(factory); ArrayNode aaData = new ArrayNode(factory); for (PkgLoad pkgLoad : pkgLoadList) { ObjectNode row = new ObjectNode(factory); row.put(“ounces”, pkgLoad.ounces); row.put(“revolutions”, pkgLoad.revolutions); aaData.add(row); } dataTable.put(“aaData”, aaData);

Jackson使用mixins以动态不同的名称序列化属性

我使用不同的NoSQL数据库,根据数据库,我需要将“id”命名为不同。 例如在OrientDB ,id被命名为“@rid” @JsonProperty(“@rid”) private String id; 对于MongoDB,id被命名为“_id” @JsonProperty(“@_id”) private String id; 我不知道现代数据库开发人员有什么问题,不只是命名id字段“id”^^。 但现在我有一个问题。 如何在某些情况下动态序列化/反序列化id字段为“@rid”,在另一种情况下为“_id”? 编辑: 基于rmullers建议我尝试使用mixins。 所以我举个例子: public interface IdMixins { } public interface MongoIdMixIn extends IdMixins { @JsonProperty(“_id”) String getId(); @JsonProperty(“_id”) void setId(String id); } public interface OrientIdMixIn extends IdMixins{ @JsonProperty(“@rid”) String getId(); @JsonProperty(“@rid”) void setId(String id); } 其中IdMixins是一个完全空的接口,用于获得更多的控制,哪些接口可以传递给映射器。 然后是一堂课: @JsonTypeInfo(use=JsonTypeInfo.Id.CLASS, include=JsonTypeInfo.As.PROPERTY, property=”@javaClass”) […]

如何使用jackson制作POJO并解析递归对象?

我有一个以下JSON响应,我从rest服务回来。 现在我需要将JSON响应下面的反序列化反转为POJO。 我正在和jackson合作。 { “pagination”: { “number”: 1, “entriesPerPage”: 200, “total”: 3 }, “postings”: [{ “categories”: [{ “taskid”: “79720”, “name”: “Sunglasses”, “parentCategory”: { “taskid”: “394”, “name”: “Sunglasses & Fashion Eyewear”, “parentCategory”: { “taskid”: “2340”, “name”: “Men’s Accessories”, “parentCategory”: { “taskid”: “10987”, “name”: “Clothing, Shoes & Accessories” } } } }] }, { “categories”: [{ “taskid”: […]