jackson deserialization json to java-objects -
here java code used fro de de-serialization, trying convert json string java object. in doing have used next code.
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(); seek { 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); } grab (jsongenerationexception e) { system.out.println(e); } grab (jsonmappingexception e) { system.out.println(e); } grab (ioexception e) { system.out.println(e); } } }
and product.java class
package ex1jackson; public class product { private string id; private string name; private string qty; @override public string tostring() { homecoming "product [id=" + id+ ", name= " + name+",qty="+qty+"]"; } }
i getting next error.
com.fasterxml.jackson.databind.exc.unrecognizedpropertyexception: unrecognized field "id" (class ex1jackson.product), not marked ignorable (0 known properties: ]) @ [source: java.io.stringreader@16f76a8; line: 1, column: 8] (through reference chain: ex1jackson.product["id"]) build successful (total time: 0 seconds)
help me slove this,
it looks trying read object json describes array. java objects mapped json objects curly braces {}
json starts square brackets []
designating array.
what have list<product>
describe generic types, due java's type erasure, must utilize typereference
. deserialization read: myproduct = objectmapper.readvalue(productjson, new typereference<list<product>>() {});
a couple of other notes: classes should camelcased. main method can public static void main(string[] args) throws exception
saves useless catch
blocks.
java json object jackson deserialization
No comments:
Post a Comment