且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

jackson反序列化json到java-objects

更新时间:2022-06-16 22:35:54

看起来你好像是尝试从JSON中读取实际描述数组的对象。 Java对象使用大括号 {} 映射到JSON对象,但是您的JSON实际上以方括号 [] 开头指定数组。

It looks like you are trying to read an object from JSON that actually describes an array. Java objects are mapped to JSON objects with curly braces {} but your JSON actually starts with square brackets [] designating an array.

实际拥有的是 List< product> 描述泛型类型,因为Java的类型擦除,您必须使用 TypeReference 。您的反序列化可以是: myProduct = objectMapper.readValue(productJson,new TypeReference< List< product>>(){});

What you actually have is a List<product> To describe generic types, due to Java's type erasure, you must use a TypeReference. Your deserialization could read: myProduct = objectMapper.readValue(productJson, new TypeReference<List<product>>() {});

其他一些注释:你的课程应该始终是CamelCased。你的main方法可以只是 public static void main(String [] args)抛出异常这可以节省你所有无用的 catch 块。

A couple of other notes: your classes should always be CamelCased. Your main method can just be public static void main(String[] args) throws Exception which saves you all the useless catch blocks.