这是我的Java代码,用于反序列化,我正在尝试将json字符串转换为java对象。为此,我使用了以下代码:
package ex1jackson; import com.fasterxml.jackson.core.JsonGenerationException; import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.ObjectMapper; import java.io.IOException; public class Ex1jackson { public static void main(String[] args) { ObjectMapper mapper = new ObjectMapper(); try { String userDataJSON = "[{\"id\":\"value11\",\"name\": \"value12\",\"qty\":\"value13\"}," + "{\"id\": \"value21\",\"name\":\"value22\",\"qty\": \"value23\"}]"; product userFromJSON = mapper.readValue(userDataJSON, product.class); System.out.println(userFromJSON); } catch (JsonGenerationException e) { System.out.println(e); } catch (JsonMappingException e) { System.out.println(e); } catch (IOException e) { System.out.println(e); } } }
和我的product.java类
package ex1jackson; public class product { private String id; private String name; private String qty; @Override public String toString() { return "Product [id=" + id+ ", name= " + name+",qty="+qty+"]"; } }
我收到以下错误。
com.fasterxml.jackson.databind.exc.UnrecognizedPropertyException: Unrecognized field "id" (class ex1jackson.product), not marked as ignorable (0 known properties: ]) at [Source: java.io.StringReader@16f76a8; line: 1, column: 8] (through reference chain: ex1jackson.product["id"]) BUILD SUCCESSFUL (total time: 0 seconds)
帮我解决这个问题
似乎您正在尝试从JSON读取一个实际描述数组的对象。Java对象使用花括号映射到JSON对象,{}但是您的JSON实际上以方括号[]指定一个数组开始。
{}
[]
您实际拥有的是一个。List<product>为了描述泛型类型,由于Java的类型擦除,您必须使用TypeReference。您的反序列化可能显示为:myProduct = objectMapper.readValue(productJson, new TypeReference<List<product>>() {});
List<product>
TypeReference
myProduct = objectMapper.readValue(productJson, new TypeReference<List<product>>() {});
其他一些注意事项:您的课程应该始终使用CamelCased。您的主要方法可以是为public static void main(String[] args) throws Exception您节省所有无用的catch块。
public static void main(String[] args) throws Exception
catch